如何使用带有Menu XML <item>的android:onClick事件?它似乎崩溃了我的程序?</item>

时间:2014-10-23 22:56:54

标签: java android xml

出于某种原因,我的程序崩溃了一次android:onClick =&#34;确认&#34;在Menu main1.xml文件中调用。我是否在MainActivity.java文件中错误地使用了该事件?

在MainActivity.java中:

当用户点击确认菜单项

时调用
int part = 0;
static String var1 = "";
static String var2 = "";
static String var3 = "";
static String var4 = "";
static String var5 = "";
static String var6 = "";
static String var7 = "";
static String var8 = "";

public void confirm(View view) {
    EditText editText2 = (EditText) findViewById(R.id.edit_message);
    String message2 = editText2.getText().toString();
    if(part == 1) {
        var1 = message2;
    }
    if(part == 2) {
        var2 = message2;
    }
    if(part == 3) {
        var3 = message2;
    }
    if(part == 4) {
        var4 = message2;
    }
    if(part == 5) {
        var5 = message2;
    }
    if(part == 6) {
        var6 = message2;
    }
    if(part == 7) {
        var7 = message2;
    }
    if(part == 8) {
        var8 = message2;
    }
}

这是在main1.xml文件(菜单文件夹)中:

item android:id="@+id/action_confirm" android:title="@string/action_confirm" app:showAsAction="withText|ifRoom" android:onClick="confirm"

错误:

10-23 16:22:40.075: W/dalvikvm(18767): threadid=1: thread exiting with uncaught exception (group=0x4176b898)
10-23 16:22:40.085: E/AndroidRuntime(18767): FATAL EXCEPTION: main
10-23 16:22:40.085: E/AndroidRuntime(18767): android.view.InflateException: Couldn't resolve menu item onClick handler confirm in class com.test.builder.MainActivity
10-23 16:22:40.085: E/AndroidRuntime(18767):    at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.<init>(SupportMenuInflater.java:242)
10-23 16:22:40.085: E/AndroidRuntime(18767):    at android.support.v7.internal.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:443)

1 个答案:

答案 0 :(得分:0)

正如@ user3431672所说,方法参数不应该是视图而是MenuItem。点击this link了解详情。