onOptionsItemSelected(MenuItem item)不起作用

时间:2017-06-26 09:19:50

标签: android android-menu

单击“菜单”项时,Toast不会显示。我在菜单中定义的按钮没有响应。

@Override
onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_menu, menu);
    MenuItem edit= menu.findItem(R.id.edit_page);
    edit.setVisible(true);
    return true;
}

@Override
onOptionsItemSelected(MenuItem item) {

    // The error was here! Sorry for my negligence
    if (id == R.id.edit_page) {
        Toast.makeText(getApplicationContext(), "Not yet implemented!", 
            Toast.LENGTH_SHORT).show();

        return true;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在方法“onOptionsItemSelected”中比较错误的ID。

0

应该是

if (id == R.id.edit_page) {

答案 1 :(得分:-1)

id未在您的代码中定义

 onOptionsItemSelected(MenuItem item) {

     int id = item.getItemId(); //Add this line 

    if (id == R.id.edit_page) {
    Toast.makeText(getApplicationContext(), "Not yet implemented!", 
        Toast.LENGTH_SHORT).show();

    return true;
    }
}