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;
}
    原文作者:喂_balabala
    原文地址: https://www.jianshu.com/p/92ea08839b48
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞