我试图得到一个菜单项的参考,但我只是不能。 这一切都在一个片段里面。
菜单:boat_accept_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.toolbar.MainActivity" >
<item
android:id="@+id/done_boat_select"
android:title="@string/done_C"
app:showAsAction="always"/>
</menu>
您可以在代码中看到评论,我无法获得参考。
代码:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.boat_accept_menu, menu);
//boatClassSelectedBtn =(View) menu.findItem(R.id.done_boat_select);
//Cannot Cast Exception
//boatClassSelectedBtn =(View) menu.findItem(R.id.done_boat_select).getActionView();
//Null reference
//boatClassSelectedBtn = menu.getItem(0).getActionView();
//Null reference
if (boatClassSelectedBtn == null) {
Log.e("boatClassSelectedBtn", "NULL!");
}
else
{
Log.i("boatClassSelectedBtn", "OK!");
}
}
有什么问题?怎么做到这一点?
答案 0 :(得分:2)
这是获取MenuItem
private MenuItem boatClassSelectedButton;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
boatClassSelectedButton = (MenuItem) menu.findItem(R.id.done_boat_select);
return true;
}
答案 1 :(得分:1)
结束:
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.boat_accept_menu, menu);
MenuItem menuItem = menu.getItem(0);
TextView doneTv = new TextView (getActivity());
doneTv.setTextView("Ok")
boatClassSelectedBtn = menuItem.getActionView();
boatClassSelectedBtn.setOnClickListener(this);
}
答案 2 :(得分:0)
试试这个。
MenuItem boatClassSelectedBtn = menu.findItem(R.id.done_boat_select);
答案 3 :(得分:0)
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_manage_clubs, menu);
MenuItem deleteItem = menu.findItem(R.id.action_delete_club);
if (!canDelete()) {
deleteItem.setVisible(false);
}
}