Can I have toolbar for each fragment separately. How to handle navigation drawer

自古美人都是妖i 提交于 2019-12-11 17:37:31

问题


In my app some pages have custom view in toolbar. Some fragment have transparent toolbar and some have coordinate layout scroll.

So I have decided to have toolbar separate for each fragment I want to know is it a good practice or not.

If someone has already done this please share code or example.


回答1:


You can use custom toolbars in your fragments. and you have to implement them separately for each fragment. First of all declare your toolbar in your fragment layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            >
<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:gravity="start"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    >

    <RelativeLayout
       // your custom toolbar layout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </RelativeLayout>


</android.support.v7.widget.Toolbar>

Then implement it in your fragment:

find it in fragment:



 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle 
    savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        //set toolbar appearance
        toolbar.setBackground(your color);

        //for create home button
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

And yes you can implement click listeners and whatever you want to do with your toolbar. For more take a look at the second answer: How to get custom toolbar



来源:https://stackoverflow.com/questions/47628279/can-i-have-toolbar-for-each-fragment-separately-how-to-handle-navigation-drawer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!