Error inflating class android.support.design.widget.TabLayout

https://stackoverflow.com/questions/31712563/error-inflating-class-android-support-design-widget-tablayout/32895215#32895215

We have 2 scenarios:

  1. 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
  1. 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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容