We have 2 scenarios:
- Our TabLayout is in the activity. If that's the case, we need to set the theme of this activity to AppCompat theme. First we need to define such theme in style.xml (it doesn't have to be 21 version).
<style name="TabAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
Then we can define the activity theme in manifest file.
<activity
android:name=".MyTabActivity"
android:theme="TabAppTheme"
/>
We don't need to do anything with our layout.xml
- Our TabLayout is inside the fragment
Similar situation but it's harder to change the theme.
First we define theme as above. Then we need to change the theme for just our TabFragment. To do this our ActivityThatHoldsTheFragment must not have a theme set to it in the manifest. It can inherit it from the application theme but can't have it set directly.
Then we have to change fragment theme in OnCreateView of this fragment:
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.TabAppTheme);
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
View view = localInflater.inflate(R.layout.fragment_main_trasy, container, false);
Whole fragment onCreateView can looks like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.TabAppTheme);
// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
View view = localInflater.inflate(R.layout.fragment_main_trasy, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.pager);
mAdapter = new TabFragment.MyAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(viewPager);
return view;
}