根据显示的片段替换工具栏布局

Ido*_*dob 21 android navigation-drawer material-design android-toolbar

我有一个带导航抽屉的活动,它取代了活动上的main_fragment_container.当显示其中一个片段时,我想更改工具栏的布局并向其添加一个微调器(并在隐藏片段时将其删除).

我的布局看起来像这样:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">

<android.support.v7.widget.Toolbar

    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    sothree:theme="@style/AppTheme.ActionBar" />

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Main layout -->
    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Nav drawer -->
    <fragment
        android:id="@+id/fragment_drawer"
        android:name="com.idob.mysoccer.ui.DrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="left|start" />
</android.support.v4.widget.DrawerLayout>
Run Code Online (Sandbox Code Playgroud)

Tap*_*boy 43

不确定你要完成什么,但我认为,如果可能的话,你应该通过让片段自定义工具栏而不是替换它来解决这个问题.您可以根据需要让片段隐藏/显示工具栏上的视图.

添加setHasOptionsMenu(true);片段OnCreateView()然后覆盖onOptionsMenuCreated()

像这样:

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.result_list, container, false);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.this_frag_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要使用工具栏执行更多特定操作,则可以使用该实例

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

  • 我仍然建议编辑工具栏而不是替换.根据活动片段隐藏/显示您的标题和微调器. (3认同)