Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

android - Change background colour of PagerTabStrip with position

I have a ViewPager, and I move between fragments using a switch and case. I can change the title per position, but I would also like to change the background colour per position.

public PagerTabStrip titleStrip;
    titleStrip.setBackgroundColor(Color.DKGRAY);

Using this in my onCreateView sets a permanent background colour. The idea I had was to use the titleStrip.setBackgroundColor(Color.DKGRAY); where I switch the fragments or change the title. But it doesn't work properly. Sometimes the colour changes, sometimes it doesn't, sometimes it changes in the wrong fragment.

This is the code where I switch fragments:

@Override
    public Fragment getItem(int position) { 

        switch (position) {

        case 0:  titleStrip.setBackgroundColor(Color.DKGRAY); // These
                 titleStrip.setTextColor(Color.WHITE); // This doesn't work either

            return new Fragment0();

        case 1:
            return new Fragment1();
        case 2:
            return new Fragment3();
        }
        return null;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, make suer you have got the titleStrip when createView:

titleStrip = (PagerTabStrip) pagerView.findViewById(R.id.pager_title_strip);

then, you can add OnPageChangeListener to ViewPager, you can do anything you want in onPageSelected method:

mPager.setOnPageChangeListener(new OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        switch (position) {
        case 0:
            titleStrip.setBackgroundColor(Color.BLUE);
            break;

        case 1:
            titleStrip.setBackgroundColor(Color.GRAY);
            break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...