处理菜单项单击事件-Android


122

我想创建一个意图,一旦单击菜单项,便会启动新活动,但是我不确定如何执行此操作。我一直在阅读android文档,但是我的实现是不正确的..一些正确方向的指导会有所帮助。我在下面列出了我的代码并注释了我的问题领域,我认为我在调用错误的方法。

package com.jbsoft.SimpleFlashlight;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SimpleFlashLightActivity extends Activity {


  Button GreenButton;   // Declare instances of buttons to use later
  Button BlueButton;

  private static final int OK_MENU_ITEM = Menu.FIRST;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    BlueButton = (Button) findViewById(R.id.bluebutton);
    BlueButton.setOnClickListener(new View.OnClickListener() {

      public void onClick(View v) {

        //Display msg when user clicks Blue Button
        showColorChangeMsg();

        // Switch Activities on click
        Intent blueintent = new Intent(SimpleFlashLightActivity.this,
                                       BlueFlashLightActivity.class);
        startActivity(blueintent);

      }
    });
    //Install listener for second button
    GreenButton = (Button) findViewById(R.id.greenbutton);
    GreenButton.setOnClickListener(new View.OnClickListener() {

      public void onClick(View v) {

        // Display msg when user clicks Green Button
        showColorChangeMsg();

        Intent greenintent = new        Intent(SimpleFlashLightActivity.this,
                                               GreenFlashLightActivty.class);
        startActivity(greenintent);

      }
    });

    ;

    /**************************************************************************************/

    // Method Declarations // THIS IS WHERE I'M HAVING A PROBLEM

    MenuItem AddColorButton = (MenuItem)findViewById(R.id.menu_insert);

    boolean onOptionsItemSelected(AddColorButton) {
      Intent intent = new  Intent(SimpleFlashLightActivity.this,
                                  BlueFlashLightActivity.class);
      startActivity(intent);
      return true;
      ;
    };
    /****************************************************************************************/

  }
  private void showColorChangeMsg()
  {
    Toast msgtoast = Toast.makeText(this.getBaseContext(), "SWITCH COLOR!",
                                    Toast.LENGTH_LONG);
    msgtoast.show();
  }
  private void showMsg(String msg) {
    Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    toast.show();
  }

  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.list_menu, menu);
    return true;

  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case OK_MENU_ITEM:
      showMsg("OK");
      break;
    }
    return super.onOptionsItemSelected(item);
  }

}

Answers:


297

用于创建菜单的简单代码。

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

选择菜单的简单代码

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

有关更多详细信息,请访问以下链接。

链接1

链接2


如果我将android:onClick属性放入XML中,该属性在这种情况下不起作用吗?(此处是非常初级的Android程序员)
FateNuller 2014年

用于选项菜单的XML内的@FateNuller onClick将不起作用,它将对布局起作用。您应该处理onOptionsItemSelected内部的操作栏选项菜单单击。
Marko 2014年

需要常量表达式。不能在Android库模块中的switch语句中使用资源ID,...在Android库模块中的switch语句中使用资源ID进行验证。自从SDK工具r14起,资源ID在库项目中就不是最终的,这意味着库代码无法将这些ID视为常量。
Zon

13

添加以下代码

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent i = new Intent(this,SecondActivity.class);
            this.startActivity(i);
            return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

5

菜单项文件看起来像

res / menu / menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/settings"
        android:title="Setting"
        app:showAsAction="never" />
    <item
        android:id="@+id/my_activity"
        android:title="My Activity"
        app:showAsAction="always"
        android:icon="@android:drawable/btn_radio"/>
</menu>

Java代码看起来像

src / MainActivity.java

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

      if (id == R.id.my_activity) {
            Intent intent1 = new Intent(this,MyActivity.class);
            this.startActivity(intent1);
            return true;
        }

        if (id == R.id.settings) {
            Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

并将以下代码添加到您的AndroidManifest.xml文件中

<activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
        </activity>

希望对您有帮助。


3

该代码对我有用

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

1

除了问题中显示的选项之外,还可以从菜单直接在xml文件中实现操作,例如:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="iraActivitySobre" />

对于Java(活动)文件,您需要使用菜单项类型的单个参数实现公共方法,例如:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

注意:此方法将具有类似于onOptionsItemSelected(MenuItem项目)的行为。


0

替换onOptionsItemSelected为:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

在这里,我想从导航DashboardActivitySettingActivity

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.