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).

Then we can define the activity theme in manifest file.


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;
}

你可能感兴趣的:(Error inflating class android.support.design.widget.TabLayout)