Android - 在ViewPager中访问TextView

时间:2016-05-12 10:44:31

标签: android android-viewpager

我正在使用带有自定义PageAdapter的标准Viewpager。

如何访问Viewpager的TextView,更改onPageSelected()的字体颜色?

编辑1:ViewPager侦听器

final ViewPager vp = (ViewPager) findViewById(R.id.a2viewpager);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int arg0) {

            }
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                vp.getParent().requestDisallowInterceptTouchEvent(true);
            }
            public void onPageSelected(final int currentPage) {
                ImageButton leftNav = (ImageButton) findViewById(R.id.a2left_nav);
                ImageButton rightNav = (ImageButton) findViewById(R.id.a2right_nav);
                int lastIdx = vpAadapter.getCount() - 1;


                if (receiptPool.get(currentPage).contains("_(Canceled)") == true){
                    vp.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorRed));
                }
                else {
                    vp.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorMainTextBackground));
                }


            }
        });

编辑1:自定义适配器

public class CustomPagerAdapter extends PagerAdapter {

    Context mContext;
    private Vector<View> pages;
    private activity1 act1;
    private activity2 act2;
    private Intent intent;

    public CustomPagerAdapter(Context context, Vector<View> pages) {
        super();
        this.act1 = new activity1();
        this.act2 = new activity2();
        this.mContext=context;
        this.pages=pages;
    }


    @Override
    public Object instantiateItem(final ViewGroup container, final int CurrentPage) {
        View page = pages.get(CurrentPage);

        page.setOnTouchListener(new View.OnTouchListener() {
            /******/

        });

        container.addView(page);
        return page;
    }


    @Override
    public int getCount() {
        return pages.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getItemPosition(Object object) {
        // Seems to be required as a workaround.
        return POSITION_NONE;
    }
}

由于

2 个答案:

答案 0 :(得分:0)

由于您使用的是自定义适配器,这意味着适配器会对viewPager中的所有项目进行充气。因此,请检查您的适配器,找到膨胀的xml,并更改文本颜色,或者在适配器内的getViewinstantiateItem方法中以编程方式执行此操作。但是,如果我们看到您的代码,那就更好了

答案 1 :(得分:0)

Viewpager必须包含多个片段,首先必须找到片段。

下面的代码显示了访问textview当前显示的片段:

DemoObjectFragment frag1 = (DemoObjectFragment)mViewPager.getAdapter().instantiateItem(mViewPager, mViewPager.getCurrentItem());

frag1.textview.setVisibility(View.VISIBLE);