Handling a Menu Item Click Event - Android

How to set On Click Listener to menu item in android studio

You don't have to setOnClickListener for each and every menu items individually.

public boolean onOptionsItemSelected(MenuItem item) method is handling all the clicks for a menu and using a switch or if condition you can find out which menu item is clicked. So all you have to do is add onClick the functionality for each item.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.navShare:
Intent shareIntent = new Intent (Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBody = "your body here";
String shareSub = "Your subject here";
shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSub);
shareIntent.putExtra (Intent.EXTRA_TEXT, shareBody);
startActivity (Intent.createChooser (shareIntent,"Share App Locker"));
return true;

case R.id.otherItem:
// Some other methods
return true;

default:
return super.onOptionsItemSelected(item);

}
}

Handling popup menu items click

Before showing the PopupMenu add a listener for PopupMenu for handling the click events.

popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});

How to add click event to item on NavigationView of Android

  1. Implement the listener in your Activity:

    public class HomeActivity extends AppCompatActivity implements 
    NavigationView.OnNavigationItemSelectedListener
  2. setNavigationItemSelectedListener in onCreate of Activity

    NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);

    if (mNavigationView != null) {
    mNavigationView.setNavigationItemSelectedListener(this);
    }
  3. Override the method

    public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_account) {
    // DO your stuff
    }
    }

android: menu item click event from fragment

If you want to capture the click on your item, implement

public boolean onOptionsItemSelected(MenuItem item)

And then:

If your activity includes fragments, the system first calls
onOptionsItemSelected() for the activity then for each fragment (in
the order each fragment was added) until one returns true or all
fragments have been called.

You can follow the oficial reference:

http://developer.android.com/guide/topics/ui/menus.html



Related Topics



Leave a reply



Submit