当我选择菜单选项一次。 onOptionsItemSelected被调用两次。 (机器人)

时间:2012-02-02 06:35:44

标签: android menu

单击我的菜单两次onoptionitemselected被调用。如何阻止它

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.docmenu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.upload:
            Log.e("testing", "called");
            return true;
      case R.id.back:
        return true;
      default:
      return super.onOptionsItemSelected(item);
     }
    }

我的菜单xml是

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/upload"
          android:icon="@drawable/menu_upload"
          android:title="@string/upload" />
    <item android:id="@+id/back"
          android:icon="@drawable/menu_back"
          android:title="@string/back" />
</menu>

选择上传图标时。在日志测试中,被打印两次。

3 个答案:

答案 0 :(得分:2)

@Override
   public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId())
    {
    case R.id.Aboutus: 
        final Dialog d1 = new Dialog(Welcome.this);
        d1.setContentView(R.layout.aboutus);

        d1.show();



        break;

并确保您已在res命名菜单下创建了文件夹。并制作新的menu.xml文件

并将这样的代码放在menu.xml文件中,如下所示:

<?xml version="1.0" encoding="utf-8"?>

 <item android:id="@+id/Aboutus"
     android:title="About Us" android:icon="@drawable/ic_menu_about_us" />

<item android:id="@+id/Settings"
     android:title="Settings" android:icon="@drawable/ic_menu_settings"/>



<item android:id="@+id/help"
    android:title="Help" android:icon="@drawable/ic_menu_help" />

答案 1 :(得分:1)

onOptionsItemSelected返回true是正确的

答案 2 :(得分:1)

试试这段代码......

@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) 
        {
        case R.id.menu_settings:
                Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_LONG).show();
            break;

        case R.id.my_settings:
            Toast.makeText(getApplicationContext(), "Home Page", Toast.LENGTH_LONG).show();
            break;
        default:
            Toast.makeText(getApplicationContext(), "Exit", Toast.LENGTH_LONG).show();
        }
        return super.onOptionsItemSelected(item);
    }

在菜单文件夹中创建一个新的xml并应用此代码。

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_settings"
        android:title="@string/menu_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
    <item android:id="@+id/my_settings"
        android:title="@string/my_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>