Iam trying to get a menu item's reference but i just cant. This whole thing is inside a fragment.
Menu: 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>
You can see the comment inside the code, i cannot get the reference.
Code:
@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!");
}
}
What is the problem? How to achieve this?
This is the correct way to get the reference of a 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;
}
Ended up:
@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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With