Handling a Menu Item Click Event - Android

AndroidEvent HandlingMenuitemOptions MenuOnitemclicklistener

Android Problem Overview


I want to create an intent that starts a new activity once a Menu Item is clicked, but I'm not sure how to do this. I've been reading through the android documentation, but my implementation isn't correct..and some guidance in the right direction would help. I've listed my code below and commented out my problem areas, I think I'm invoking the wrong method.

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

}

Android Solutions


Solution 1 - Android

Simple code for creating menu.

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

Simple code for menu item selection

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

You can find more detail from below link..

Menus

Menu resource

Solution 2 - Android

Add Following Code

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

Solution 3 - Android

Menu items file looks like

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 code looks like

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

And add following code to your AndroidManifest.xml file

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

I hope it will help you.

Solution 4 - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

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

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

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

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

Solution 5 - Android

This code is work for me

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

Solution 6 - Android

Replace Your onOptionsItemSelected as:

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

Here, I want to navigate from DashboardActivity to SettingActivity.

Solution 7 - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJade ByfieldView Question on Stackoverflow
Solution 1 - AndroidNiranj PatelView Answer on Stackoverflow
Solution 2 - AndroidHalf MoonView Answer on Stackoverflow
Solution 3 - AndroidPacific P. RegmiView Answer on Stackoverflow
Solution 4 - AndroidJackson.RoberioView Answer on Stackoverflow
Solution 5 - AndroidBasantView Answer on Stackoverflow
Solution 6 - AndroidDinesh KcView Answer on Stackoverflow
Solution 7 - AndroidBercoveView Answer on Stackoverflow