0

我想在片段中的 textview 中更改文本,我可以在 instantiateItem 中轻松做到这一点,但是在 instantiateItem 之后,textView 为空,我无法调用

MyPagerAdapter.textView.SetText();

private class MyPagerAdapter extends PagerAdapter {


        TextView textView;

        public int getCount() {
            return 5;
        }

        public Object instantiateItem(View collection, int position) {

            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            int resId = 0;
            switch (position) {
            case 0:
                resId = R.layout.farleft;
                 View view = inflater.inflate(resId, null);
                ((ViewPager) collection).addView(view, 0);
                 textView = (TextView)view.findviewById(R.id.textvvvv);
                 return view;

            case 1:
                resId = R.layout.left;
                break;
            case 2:
                resId = R.layout.middle;
                break;
            case 3:
                resId = R.layout.right;
                break;
            case 4:
                resId = R.layout.farright;
                break;
            }


        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);

        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == ((View) arg1);

        }

        @Override
        public Parcelable saveState() {
            return null;
        }
}

但是,当我用

textView.SetText("EEE");

它运行良好,但我无法更改 MyPageAdapter 之外的文本,为什么?

4

2 回答 2

0

MyPagerAdapter不是static,您的访问方法将用于静态类。尝试实例化PagerAdapter并使用该引用来调用该getAdapter()方法并尝试使用findViewById(....)

编辑:

当您PagerAdapter在活动中声明时,尝试从中获取适配器的引用,如下所示

PagerAdapter viewer = (PagerAdapter) findViewById(R.id.pageradapter);-->

viewer.getAdapter().findViewById(...)
于 2012-06-05T05:47:49.097 回答
0

ViewPager 从 View 继承 findViewById(),所以你不能这样做:

TextView textView = (TextView) viewPager.findViewById(...);
于 2012-06-05T09:12:55.377 回答