Search code examples
androidandroid-viewpagerandroid-pageradapter

PagerSlidingTabStrip Changing colour of the indicator


Hi I am using PagerSlidingTabStrip for showing tabs in viewpager. I have to change the colour of the indicator from red to green when the user slides from 1st to 2nd fragment. The transition of colors has to be a smooth one. But I am not able to decide how I can do it. Please Help !!! Thanks in advance!!!!


Solution

  • Try this!

    int NTABS = 2;
    int[] COLORS = { 0xFFFF0000, 0xFF00FF00 }; // COLORS.length == NTABS
    
    mPagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mPagerSlidingTabStrip.setIndicatorColor(getNewColor(position, positionOffset));
        }
    
        @Override public void onPageSelected(int position) {
    
        }
    
        @Override public void onPageScrollStateChanged(int state) {
    
        }
    });
    
    
    private int getNewColor(int position, float offset) {
        int next;
        if (offset > 0) next = (position < NTABS) ? position+1 : position;
        else next = (position > 0) ? position-1 : 0;
        return blendColors(COLORS[next], COLORS[position], offset);
    }
    
    public int blendColors(int color1, int color2, float ratio) {
        final float inverseRation = 1f - ratio;
        float a = (Color.alpha(color1) * ratio) + (Color.alpha(color2) * inverseRation);
        float r = (Color.red  (color1) * ratio) + (Color.red  (color2) * inverseRation);
        float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
        float b = (Color.blue (color1) * ratio) + (Color.blue (color2) * inverseRation);
        return Color.argb((int) a, (int) r, (int) g, (int) b);
    }