简体   繁体   English

我可以分别为每个片段设置工具栏吗? 如何处理导航抽屉

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

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.如果有人已经这样做了,请分享代码或示例。

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 background);

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

  return view;
}

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有关更多信息,请查看第二个答案: 如何获取自定义工具栏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM