Search code examples
androidtabspagerslidingtabstrip

How to change tab background color programmatically?


I am trying to change the background color of selected (active tab). My case is by default all tabs are white when user select the tab it gets the color I want. I am using a library name PagerSlidingTabStrip ... what I tried so far is:

On tab change I call this code. It works very fine and change the text color. Now all I want to change the same tab background color.

private void setSelectedTabColor(int position) {
    for(int i=0; i<tabStrip.getChildCount(); i++)  
    {  
        LinearLayout view = (LinearLayout) tabStrip.getChildAt(0);
        TextView textView = (TextView) view.getChildAt(i);
        textView.setTextColor(getResources().getColor(R.color.black)); 
    }  

    LinearLayout view = (LinearLayout) tabStrip.getChildAt(0);
    TextView textView = (TextView) view.getChildAt(position);
    textView.setTextColor(getResources().getColor(R.color.white));
}

By trying the below code in loop, I get null pointer exception.

tabStrip.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.dash_bar));

Solution

  • Add these lines to change the background of particular child.

    LinearLayout view = (LinearLayout) tabStrip.getChildAt(0);      
    TextView textView = (TextView) view.getChildAt(position);
    textView.getParent().setBackgroundColor(getResources().getColor(
                  R.color.dash_bar));