How to change Viewpager tab colour dynamically?

前端 未结 3 654
猫巷女王i
猫巷女王i 2021-01-20 18:26

How to change colour of Tabs like this? When I click/swipe to green or any other tab, the tab colour should change to that appropriate colour and rest of other tabs colour

3条回答
  •  我在风中等你
    2021-01-20 18:44

    I had a similar problem. In my case, I wanted to change the color of the action bar whenever the user clicked on one of the fragments in the navigation drawer.

    Here is the code I used to resolve this issue.

    Since you can't access the Action bar from a fragment, you have to create it in your main menu. Here is the method I used.

    public void restoreActionBar(int parsedColor) {
            this.parsedColor = parsedColor;
            ActionBar actionBar = getSupportActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setTitle(mTitle);
            actionBar.setBackgroundDrawable(new ColorDrawable(parsedColor));
    
        } 
    
    public boolean onCreateOptionsMenu(Menu menu) {
            if (!mNavigationDrawerFragment.isDrawerOpen()) {
                // Only show items in the action bar relevant to this screen
                // if the drawer is not showing. Otherwise, let the drawer
                // decide what to show in the action bar.
                getMenuInflater().inflate(R.menu.main_activity_trekkly, menu);
                restoreActionBar(parsedColor);
                return true;
            }
            return super.onCreateOptionsMenu(menu);
        }
    

    Now in your class that extends fragment:

    public void onAttach(Activity activity) {
                super.onAttach(activity);
    
                ((MainActivityTrekkly)activity).onSectionAttached(4);
                MainActivityTrekkly mA = ((MainActivityTrekkly)getActivity());
    
                mA.restoreActionBar(Color.parseColor("#028482"));
            }
    

    I got this working with the Navigation drawer so you might have to adapt this code.

    Did this help?

提交回复
热议问题