Ajay Ajay - 3 months ago 17
Android Question

Change Tablayout Bacground Color While Scrolling

I am Developing an android app that having 3 tabs. I am using

TabLayout
and
ViewPager
. I planed to give 3 different background colours for The AppBar & TabLayout on 3 different tabs. I need to make a smooth transmission between colours while changing the tabs by scrolling or by clicking on the tabs. How you make this transmission? Can anybody Help me?

Answer

I make sample. hope this helps.

enter image description here

In your Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);

    int[] colors = {Color.RED, Color.GREEN, Color.BLUE};
    viewPager.setAdapter(new MyAdapter());
    viewPager.addOnPageChangeListener(new HeaderColorChanger(tabLayout, colors));
    tabLayout.setupWithViewPager(viewPager);
}

MyAdapter is like this:

class MyAdapter extends PagerAdapter {

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        TextView view = (TextView) LayoutInflater
                .from(container.getContext())
                .inflate(R.layout.row_item, container, false);
        container.addView(view);
        view.setText("Page:" + position);
        return view;
    }

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

    @Override
    public int getCount() {
        return 3;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return "Page:" + position;
    }
}

HeaderColorChanger is like this:

class HeaderColorChanger implements ViewPager.OnPageChangeListener {

    private ArgbEvaluator argbEvaluator = new ArgbEvaluator();
    private View mView;
    private int[] mColors;

    HeaderColorChanger(View view, int[] colors) {
        mView = view;
        mColors = colors;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mView.setBackgroundColor(getHeaderColor(position, positionOffset));
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private int getHeaderColor(int position, float positionOffset) {
        if (position == mColors.length - 1) {
            return mColors[position];
        }
        int startColor = mColors[position];
        int endColor = mColors[position + 1];
        int color = (int) argbEvaluator.evaluate(positionOffset, startColor, endColor);
        return color;
    }
}