Android 根据显示的片段替换工具栏布局
我有一个带有导航抽屉的活动,它替换了活动上的主\u fragment\u容器。 当其中一个片段显示时,我想更改工具栏的布局,并向其添加微调器(并在片段隐藏时将其删除) 我的布局如下所示:Android 根据显示的片段替换工具栏布局,android,navigation-drawer,material-design,android-toolbar,Android,Navigation Drawer,Material Design,Android Toolbar,我有一个带有导航抽屉的活动,它替换了活动上的主\u fragment\u容器。 当其中一个片段显示时,我想更改工具栏的布局,并向其添加微调器(并在片段隐藏时将其删除) 我的布局如下所示: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:sothree="http:/
<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>
不确定您想要完成什么,但我认为,如果可能的话,您应该让这些片段定制您的工具栏,而不是替换它。您可以根据需要让片段在工具栏上隐藏/显示视图 添加
设置选项菜单(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);
}
如果需要使用工具栏执行更具体的操作,可以使用
Toolbar-Toolbar=(Toolbar)findviewbyd(R.id.Toolbar)代码>以上J.G.Sebring的答案(已接受的答案)有效,但它保留了两个选项菜单。前一个和新的。要保留为片段创建的新菜单,可以添加menu.clear()
我有两个不同的工具栏,带标题的标准工具栏和带微调器而不是标题的工具栏。我只想在显示我的一个片段时使用微调器显示工具栏。我仍然建议编辑工具栏而不是替换。根据活动片段隐藏/显示标题和微调器。一个工具栏的实现效果很好!谢谢,请编辑你的答案,我会把它标记为answeredNice,很高兴我能帮上忙。我的回答明确建议编辑现有工具栏,而不是替换它。这是第一句话。不确定要编辑什么?最后,解决方案是使用一个“完整”工具栏,并根据显示的片段隐藏\显示相关微调器这将使工具栏下方的抽屉打开。重叠工具栏(但现在连Google Play都不这么做)。我是故意这样做的,在我的设计中,抽屉在工具栏上时看起来不太好。
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.settings_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}