[英]Android Toolbar, how to hide and show fragments
I have a ToolBar (android.support.v7.widget.Toolbar) which has 2 clickble icons which are meant to display their own views. 我有一个ToolBar(android.support.v7.widget.Toolbar),其中有2个clickble图标,用于显示自己的视图。
I thought that, the main activity which hosted the ToolBar, and held the onCreateOptionsMenu(), onOptionItemSelected() etc methods, should then have 2 fragments, corresponding to the icons. 我认为,承载ToolBar并保留onCreateOptionsMenu(),onOptionItemSelected()等方法的主要活动应具有2个对应于图标的片段。 So when I click on one icon, and then to another, the relevant fragments should be hidden/shown. 因此,当我单击一个图标,然后单击另一个图标时,相关的片段应被隐藏/显示。 Is this the correct way to go forward? 这是前进的正确方法吗? Or am I meant to use intents? 还是我打算使用意图?
I also thought of using a FragmentStatePager adapter with a ViewPager but I am unsure if that is a possibility, since this is a ToolBar and not a seperate sliding mechanism to travel from Fragment A -> Fragment B and vice versa. 我还考虑过将FragmentStatePager适配器与ViewPager一起使用,但是我不确定这是否可行,因为这是ToolBar,而不是从Fragment A-> Fragment B传播的单独滑动机制,反之亦然。
Add a FrameLayout
in your activity: 在活动中添加一个FrameLayout
:
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and then swap out the Fragments when a Toolbar button is clicked, like this: 然后在单击“工具栏”按钮时换出片段,如下所示:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.menu_item_1) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment1)
.commit();
} else if(id == R.id.menu_item_2) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment2)
.commit();
}
return super.onOptionsItemSelected(item);
}
Obviously you will have to init your fragments beforehand and probably add a check to see if a certain fragment is already displayed before you do a transaction. 显然,您必须事先初始化片段,并可能在执行事务之前添加检查以查看某个片段是否已经显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.