Search code examples
androidonclicklistener

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


I try to set share item using Navigation Drawer Activity in android studio,

 <menu>
        <item
            android:id="@+id/navShare"
            android:icon="@drawable/ic_menu_share"
            android:title="Share" />

this is the xml code for that.

problem was come when I try to write java code for this propose, problem is what is the typecast type of this navShare menu item in this java code.

} else if (id == R.id.navShare) {

               share  = () findViewById (R.id.navShare);
        share.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            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"));

Solution

  • 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);
    
      }
    }