我的要求很简单,我想打开片段中的menuItem列表。因此,我在菜单内部创建了菜单XML,并尝试在Fragment的 onCreateOptionsMenu 方法内部进行充气,但不幸的是没有任何显示。
这里是:
myFragment.java
public static MoreFragment newInstance() {
return new MoreFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.more_drawer, menu);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true);
View v = inflater.inflate(R.layout.fragment_more, container, false);
setUp(v);
return v;
}
在这里, more_drawer.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_busTracking"
android:icon="@drawable/ic_more_drawer_bus_tracking"
android:title="Bus Tracking" />
<item
android:id="@+id/nav_kidsWallet"
android:icon="@drawable/ic_more_drawer_kids_wallet"
android:title="Kids' Wallet" />
<item
android:id="@+id/nav_circlals"
android:icon="@drawable/ic_more_drawer_circulars"
android:title="Circulars" />
<item
android:id="@+id/nav_message"
android:icon="@drawable/ic_more_drawer_messages"
android:title="Messages" />
<item
android:id="@+id/nav_accountSettingd"
android:icon="@drawable/ic_more_drawer_account_settings"
android:title="@string/account_settings" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/ic_more_drawer_logout"
android:title="Log Out" />
</menu>
fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
</RelativeLayout>
我尝试将 setHasOptionsMenu(true)放在onCreate()和onCreateView()中,但是什么也没显示。
我尝试调试,发现未调用 onCreateOptionsMenu()。我尝试了为该问题提供的所有解决方案,但没有任何帮助。
我在做什么错了?
答案 0 :(得分:0)
更改此:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.more_drawer, menu);
}
收件人:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.more_drawer, menu);
super.onCreateOptionsMenu(menu, inflater);
}
然后在视图膨胀创建后使用:setHasOptionsMenu(true);
:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
答案 1 :(得分:0)
您检查了清单文件吗?
确保为活动选择的主题包括操作栏。 例如:android:theme =“ @ style / Theme.AppCompat”>