根据所显示的片段替换工具栏布局 [英] Replace toolbar layout according to the displayed fragment
问题描述
我有一个抽屉式导航,可取代main_fragment_container上的活动的活动。 当显示片段中的一个我想更改工具栏的布局,并添加微调给它(并删除它时,该片段是隐藏的)。
I have an activity with navigation drawer which replace the main_fragment_container on the activity. When one of the fragments is displayed I want to change the layout of the toolbar and add a spinner to it (and remove it when the fragment is hidden).
我的布局看起来像这样:
My layout looks like that:
<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>
推荐答案
不知道你想什么来完成,但我认为,如果可能的话,你应该让段自定义工具栏,而不是取代它接近这一点。你可以让你的碎片隐藏/显示视图的工具栏上根据自己的需要。
Not sure what you are trying to accomplish but I think, if possible, you should approach this by letting the fragments customize your toolbar rather than replacing it. Your can let your fragments hide/show views on the toolbar depending on your needs.
添加 setHasOptionsMenu(真);
中的片段 OnCreateView()
,然后覆盖 onOptionsMenuCreated()
Add setHasOptionsMenu(true);
in the fragments OnCreateView()
and then override 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);
}
如果您需要在工具栏做更具体的东西,你可以用获取实例
If you need to do more specific things with the toolbar you can get the instance using
工具栏=(栏)findViewById(R.id.toolbar);
这篇关于根据所显示的片段替换工具栏布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!