Reputation: 467
Dear can we use onclick with menu item in xml. like below .i tried it but its not working.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/logout"
android:onClick="onLogOut"
android:title="@string/logout">
</item>
Java Code :
public void onLogOut(MenuItem v) {
Utility.LogError(TAG, "onLogOut Clicked");
Toast.makeText(this, "onLogOut", Toast.LENGTH_SHORT).show();
}
}
onLogOut is not get called....
Upvotes: 3
Views: 8170
Reputation: 66
Have you tried it already to make it work with the onOptionItemSelected() function?
onOptionsItemSelected
Added in API level 1
boolean onOptionsItemSelected (MenuItem item)
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Edit:
I also found this for Handling click events
Handling click events
To perform an action when the user selects a menu item, you must implement the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by calling setOnMenuItemclickListener(). When the user selects an item, the system calls the onMenuItemClick() callback in your interface.
For example (example is from the website):
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.actions);
popup.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.archive:
archive(item);
return true;
case R.id.delete:
delete(item);
return true;
default:
return false;
}
}
So probably if you inset the onOptionsItemSelected or the onMenuItemClick you should be able to receive a call from the onLogOut.
Upvotes: 1
Reputation: 30168
That's because that only works for XML layouts, that there is a menu. For menus you should override the onItemMenuSelected()
method. Read the documentation.
Edit:
Whoops! Apparently it is possible but only with Honeycomb and later.
Upvotes: 0
Reputation: 132972
use
android:onClick="onLogOutClick"
instead of
android:onClick="@string/onLogOutClick"
for adding onclick with menu item
and And in Java we should write the method for this onlick
public void onLogOutClick(MenuItem item) {
Log.d("MenuItem", "onLogOutClick :: "+item.getItemId());
}
Upvotes: 7