如何在Android中以编程方式触发/单击MenuItem? [英] How to programmatically trigger/click on a MenuItem in Android?

查看:234
本文介绍了如何在Android中以编程方式触发/单击MenuItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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/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" />
</menu>

而我的onOptionsItemSelected方法中有这个:

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

我尝试过:

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

但是actionRestart参考没有提供clicktrigger等之类的东西.

But actionRestart reference doesn't offer anything like click, trigger, etc.

我还要指出,我是Android开发的新手,并且来自PHP/JavaScript背景,因此Java OOP的这一级别对我来说是新的.

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.

推荐答案

使用方法 performIdentifierAction , 像这样:

menu.performIdentifierAction(R.id.action_restart, 0);

这篇关于如何在Android中以编程方式触发/单击MenuItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆