Inflating AppBarLayout with Toolbar + TabLayout

I modified the solution given by bleeding182 and got it to work for AppBarLayout as well (to resolve the problem pointed out by bopa).

@Override
public void onAttach(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getActivity().findViewById(R.id.appbar).setElevation(0);
    }
    super.onAttach(context);

}

@Override
public void onDetach() {
    super.onDetach();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getActivity().findViewById(R.id.appbar).setElevation(R.dimen.toolbar_elevation);
    }
}

What I did was replace the call to getSupportActionBar() by giving an ID to my AppBarLayout and then calling findViewById() on it and then calling setElevation on its result. Tested on API 23.


I had a similar issue where I wanted a TabLayout just inside of one fragment.

Without changing any other code you can solve this by using onAttach and onDetach inside your fragment with the TabLayout.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // todo add some further checks, e.g. instanceof, actionbar != null

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ((AppCompatActivity) activity).getSupportActionBar().setElevation(0);
    }
}

@Override
public void onDetach() {
    super.onDetach();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ((AppCompatActivity) getActivity()).getSupportActionBar()
                .setElevation(getResources().getDimension(R.dimen.toolbar_elevation));
    }
}

Be sure to set the same elevation on your TabLayout and everything works fine! ;D


You are able to have separate toolbar for each fragment. Its possible to set fragments toolbar as activity actionbar. Example code:

Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar);
 ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

It should be possible to have titles, icons and other stuff as well. With it you can mimic shadow on pre lollipop devices, no matter what you have on them.


You can simply add TabLayout programmatically from Fragment in wich you need TabLayout

tabLayout = (TabLayout) inflater.inflate(R.layout.tablay, null);
appBarLayout = (AppBarLayout) getActivity().findViewById(R.id.appbar);
appBarLayout.addView(tabLayout, new LinearLayoutCompat.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

and remove TabLayout from AppBar in onDetach()

@Override
public void onDetach() {
    appBarLayout.removeView(tabLayout);
    super.onDetach();
}