Android工具栏,如何隐藏和显示片段

时间:2016-04-18 22:10:52

标签: android android-fragments android-toolbar

我有一个ToolBar(android.support.v7.widget.Toolbar),它有2个可点击图标,用于显示自己的视图。

我认为,托管ToolBar并保持onCreateOptionsMenu(),onOptionItemSelected()等方法的主要活动应该有2个片段,对应于图标。因此,当我单击一个图标,然后单击另一个图标时,应隐藏/显示相关片段。这是正确的前进方式吗?或者我打算使用意图?

我还想过将FragmentStatePager适配器与ViewPager一起使用,但我不确定这是否可能,因为这是一个ToolBar,而不是从Fragment A传播的单独滑动机制 - >片段B,反之亦然。

1 个答案:

答案 0 :(得分:0)

在您的活动中添加FrameLayout

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

然后在单击工具栏按钮时换出片段,如下所示:

@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);
}

显然,您必须事先初始化您的片段,并且可能会在执行交易之前添加一个检查以查看是否已显示某个片段。