如何在android中的自定义视图中处理后退按钮?

时间:2017-03-14 15:23:19

标签: android android-custom-view keylistener

 relativeLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {                
                if( keyCode == KeyEvent.KEYCODE_BACK) {               
                       do....something                   
                }
                return false;
            }

}

此代码无效。当我按下后退按钮时,它没有显示任何响应。请有人帮帮我。提前谢谢......

2 个答案:

答案 0 :(得分:3)

你几乎就在那里,但这是你需要做的事情。

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

答案 1 :(得分:0)

@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覆盖方法。