Just set your custom view at the tab creation time, something like:
final Tab firstTab = actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(0))
.setCustomView(R.id.custom_tab_view_red);
final Tab secondTab = actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(1))
.setCustomView(R.id.custom_tab_view_blue);
// etc
actionBar.addTab(firstTab);
actionBar.addTab(secondTab);
// etc
in inCreate()
.
You’ll also have to define View
s corresponding to the above id
s in your xml layout file (and not style
s).
Or, if you want to create the view directly:
final View firstCustomView = new CustomView(this);
firstCustomView.setBackgroundColor(Color.BLUE); // or with drawable or resource
final Tab firstTab = actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(0))
.setCustomView(firstCustomView);
actionBar.addTab(firstTab);
// then same for other tabs, just with another color
Leaving the below information for reference:
To define one such view, you need to specify it an Android Context
. This is usually the Activity
where the tabs will be displayed.
Supposing that you initialize your tabs in an Activity
, simply pass the Activity
instance as a Context
:
ctv = new CustomView(this, R.attr.tabStyleAttr);
if from inside the Activity
, or for example:
ctv = new CustomView(getActivity(), R.attr.tabStyleAttr);
if from inside a Fragment
, etc.
As for setting a specific style for action bar tabs, no need to go create a custom view programmatically as you’re trying to. Read up a little about the action bar first, then check the example they provide. As you can see, you’ll be able to specify the tab style in xml:
In your manifest file, you can apply the theme to your entire app:
<application android:theme="@style/CustomActionBarTheme" ... />
Or to individual activities:
<activity android:theme="@style/CustomActionBarTheme" ... />
for example.
For a complete example matching perfectly your use case, see this Android doc article: https://developer.android.com/training/basics/actionbar/styling.html#CustomTabs . Notice the usage of state-lists to achieve the “when selected style”.