relativeLayout.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK) {
do....something
}
return false;
}
}
此代码不起作用。当我按下后退按钮时,它没有显示任何响应。请任何人帮助我。预先感谢......
你已经快到了,但这正是你需要做的。
relativeLayout.setFocusableInTouchMode(true);
relativeLayout.requestFocus();
relativeLayout.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if(You have handled the back press in your View){ return true; }
return false;
}
});
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
// do stuff on back key press event
return true;
}
return super.onKeyDown(keyCode, event);
}
同样,您可以根据您的要求使用 onkeyup 覆盖方法。
((上下文为?ContextWrapper)?.baseContext为?Activity)?.onBackPressed()