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 should change to black. How can I do this? Im using Viewpager.
I tried this code inside onpagelistener:
if(position == 0) {
viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.red);
}
else if(position == 1) {
viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.green);
}
But above code has no effect.
And Im using this code : Android Viewpager tutorial Androidhive
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.
Now in your class that extends fragment:
I got this working with the Navigation drawer so you might have to adapt this code.
Did this help?
There is tutorial Styling tabs in the Android action bar. You can choose your
parent theme
asTheme.Holo
for API>=3, orTheme.AppCompat
for support library V7, etc.And besides, for
<item name="android:background">
, you could set it to a selector you create for tab state change:For
selector_tab
can be like:[UPDATE]
For change tab color dynamically, suggest to use custom view with tab:
then
setCustomeView(customView)
when add tab toActionBar
. And in your tab/page change listener:To remove possible gap around tab caused by custom view, you can set tab style:
and use your theme parent accordingly.
Hope this help!
Finally I solved it. Thanks to @Xcihnegn for his idea. This is the solution:
When one tab gets unselected, setCustomView(null) changes its layout back to its original black colour. So only selected tabs will change colour. Unselecting the tabs will change its layout to original form.
To remove unnecessary padding appear when setting the custom view we should use this code in styles.xml.
Dont forget to add the this code just above setcontentview in your activity.
Custom layout for tabs.