[android] Handling a Menu Item Click Event - Android

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

}

The answer is


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

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)


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.


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.


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

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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected? How to add "active" class to wp_nav_menu() current menu item (simple way) How do I hide a menu item in the actionbar? Handling a Menu Item Click Event - Android android: changing option menu items programmatically How to change menu item text dynamically in Android Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation Android: How to enable/disable option menu item on button click? How to change the Text color of Menu item in Android? How do I center align horizontal <UL> menu?

Examples related to options-menu

Handling a Menu Item Click Event - Android

Examples related to onitemclicklistener

OnItemClickListener using ArrayAdapter for ListView How to get row count in sqlite using Android? How to handle the click event in Listview in android? Action Bar's onClick listener for the Home button Android: No Activity found to handle Intent error? How it will resolve Handling a Menu Item Click Event - Android How to handle ListView click in Android