4

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"));
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Sameera
  • 47
  • 1
  • 1
  • 6
  • https://stackoverflow.com/a/7480103/472336 check this – Pramod Oct 29 '18 at 10:51
  • I recall that Android Studio can create a SampleActivity for you by right click on project -> new -> Activity -> select the sample with menu. – Wesely Oct 29 '18 at 13:18

1 Answers1

6

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

  }
}
Nuwan Alawatta
  • 1,812
  • 21
  • 29