Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabLayout : Set custom color for each tab

I saw a lot of questions that say how to set the color differently for selected(active) and unselected(inactive) tabs. I also know that google provides void setTabTextColors (int normalColor, int selectedColor) to achieve this.

My requirement is a little different, I am working on a quiz app with a TabLayout and CardView. TabLayout allows the user to navigate between questions and CardView is used to display the questions.

I need to set the color of the tabs for which the user has already selected an answer differently than that for which the user has not answered yet. By default the TextColor is black but if the user selects an answer then the tabcolor should change to blue (just for eg.) and it should remain that way till the user exits. I have a int array called Select that will hold the value of the option that the user has selected (The values range between 1 - 4). While allocating the Select array I also initialize it with -1. I thought of setting up a loop and then if the array is -1 leave the tab as it is or set the tabcolor to blue.

How can I achieve this functionality?

like image 516
Nirmal Raj Avatar asked Dec 07 '16 15:12

Nirmal Raj


1 Answers

You can work with TabLayout internals by querying for this children and changing TextViews manually. This can break your code when you upgrade to another support library version, but as long as you keep track and test when updating, it should work:

private void updateTabTextColors() {
    LinearLayout tabsContainer = (LinearLayout) mTabLayout.getChildAt(0);
    for (int i = 0; i < mTabLayout.getTabCount(); i++) {
        LinearLayout item = (LinearLayout) tabsContainer.getChildAt(i);
        TextView tv = (TextView) item.getChildAt(1);
        tv.setTextColor(Select[i] == -1 ? Color.BLACK : Color.BLUE);
    }
}
like image 86
Marcelo Liberato Avatar answered Oct 12 '22 20:10

Marcelo Liberato