Search code examples
androidlayoutcolorsruntimeappbar

Runtime change of AppBarLayout color


How does Android Google Play app change color dynamically on user clicks on AppBarlayout?

enter image description here API 21 Lollipop I have tried the following

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab)
    {
        setTheme(R.style.AppTheme_2);
    }
}

<style name="AppTheme_2" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary_2</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_2</item>
    <item name="colorAccent">@color/colorAccent_2</item>
</style>

Solution

  • You need to get the tab position in order to manipulate the color. Here is the example.

     mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.e(TAG, String.valueOf(tab.getPosition()));
    
                switch (tab.getPosition()){
                    case 0:
                        mAppBar.setBackgroundResource(R.color.colorPrimary);
                        break;
                    case 1:
                        mAppBar.setBackgroundResource(R.color.colorPrimary);
                        break;
                    case 2:
                        mAppBar.setBackgroundColor(Color.BLACK);
                        break;
                }
            }