Ajay Ajay - 1 year ago 83
Android Question

Change Tablayout Background Color While Scrolling

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

. 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 Source

I make sample. hope this helps.

enter image description here

In your Activity:

protected void onCreate(Bundle savedInstanceState) {

    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));

MyAdapter is like this:

class MyAdapter extends PagerAdapter {

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

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

    public int getCount() {
        return 3;

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

    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;

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

    public void onPageSelected(int position) {

    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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download