按下选项按钮时如何调用Toast

时间:2016-03-14 11:47:37

标签: android android-layout android-button

这里通过选项按钮我的意思是大多数Android设备上的硬按钮,其图像是

enter image description here

通过这种方式按下后退按钮时我可以这样做: -

@Override
public void onBackPressed(){
    Toast.makeText(MainActivity.this,"Back button is pressed",Toast.LENGTH_SHORT).show();
    return;
}

1 个答案:

答案 0 :(得分:0)

您指的是选项按钮,但您编写的代码会在后退按钮上调用。你应该这样做

@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
            Toast.makeText(MainActivity.this,"Back button is pressed",Toast.LENGTH_SHORT).show();
            return true; //prevent this event from being propagated further
    }
    return super.onKeyDown(keycode, e);
}