如何在android studio中设置“单击侦听器”菜单项

如何在android studio中设置“单击侦听器”菜单项,android,onclicklistener,Android,Onclicklistener,我尝试在android studio中使用导航抽屉活动设置共享项 <menu> <item android:id="@+id/navShare" android:icon="@drawable/ic_menu_share" android:title="Share" /> 您不必分别为每个菜单项设置ClickListener public boolean onoptions ite

我尝试在android studio中使用导航抽屉活动设置共享项

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

您不必分别为每个菜单项设置ClickListener

public boolean onoptions items selected(MenuItem item)
方法处理菜单的所有单击操作,并使用
开关或
条件(如果
条件),您可以找到单击的菜单项。因此,您所要做的就是为每个项目添加onClick功能

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

  }
}

选中此项我记得Android Studio可以通过右键单击project->new->Activity->select the sample with menu为您创建一个SampleActivity。
@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);

  }
}