Android Fragment的选项菜单不显示

时间:2017-03-26 14:24:56

标签: android android-fragments

我有一个片段,我想在活动的容器中显示。问题是片段的菜单选项没有显示出来。 这是我添加片段的活动代码:我尝试了.add和.replace但两个结果相同:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    GridFragment gridFragment = new GridFragment();

    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, gridFragment, TAG_GRID_FRAGMENT)
            .commit();
}

活动的xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container" 
android:layout_height="match_parent"
android:layout_width="match_parent"
tools:context="appfactory.app.movies.ui.MainActivity"
app:sharedElementTransitions="true" />

这是片段的onCreate:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

片段的onCreateOptionsMenu:

    @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.main_fragment, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

只有当我在主xml中对片段进行硬编码时才显示片段的菜单,我不想这样做。感谢任何建议。

1 个答案:

答案 0 :(得分:1)

在菜单super.onCreateOptionsMenu(menu, inflater)clear()方法之前调用inflate()

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);    
    menu.clear();
    inflater.inflate(R.menu.main_fragment, menu);

}