Duvdevan Duvdevan - 1 year ago 158
Android Question

How to programmatically trigger/click on a MenuItem in Android?

I have these menu items in my


<menu xmlns:android="http://schemas.android.com/apk/res/android"

<item android:id="@+id/action_restart" android:title="Restart"
android:orderInCategory="1" />
<item android:id="@+id/action_clear" android:title="Clear"
android:orderInCategory="2" />
<item android:id="@+id/action_update" android:title="Update"
android:orderInCategory="3" />
<item android:id="@+id/action_about" android:title="About"
android:orderInCategory="4" />
<item android:id="@+id/action_try_restart" android:title="Try Restart"
android:orderInCategory="5" />

And I have this in my

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

if (id == R.id.action_restart) {
Toast.makeText(MainActivity.this, "Restart...", Toast.LENGTH_LONG).show();

if (id == R.id.action_clear) {
Toast.makeText(MainActivity.this, "Clear...", Toast.LENGTH_LONG).show();

if (id == R.id.action_update) {
Toast.makeText(MainActivity.this, "Update...", Toast.LENGTH_LONG).show();

if (id == R.id.action_about) {
Toast.makeText(MainActivity.this, "About...", Toast.LENGTH_LONG).show();

if(id == R.id.action_try_restart) {
// how to click / trigger the "action_restart" from here?

return super.onOptionsItemSelected(item);

I have tried with:

MenuItem actionRestart = (MenuItem) findViewById(R.id.action_restart);
actionRestart; //

reference doesn't offer anything like
, etc.

I'd also like to note that I'm new to Android development and I come from PHP/JavaScript background, so this level of Java OOP is all new to me.

Answer Source

As far as I know, there is no mechanism in the SDK that lets you do this. It's certainly not standard practice to do this sort of thing.

I recommend decoupling your logic from the actual UI as much as possible, so you end up not needing to simulate a click to trigger the action. Since you're a Web developer, this should come fairly easily to you.

In this case, you'd want to refactor the toasts into a separate method (or multiple methods), and then call that both when the menu item is clicked and when you want to trigger it manually.

Alternatively, you could try taking the MenuItem returned by findViewById() and passing it to your handler there. But I have no idea if that'll work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download