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

问题描述 投票:0回答:3
 relativeLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {                
                if( keyCode == KeyEvent.KEYCODE_BACK) {               
                       do....something                   
                }
                return false;
            }

}

此代码不起作用。当我按下后退按钮时,它没有显示任何响应。请任何人帮助我。预先感谢......

android android-custom-view keylistener
3个回答
5
投票

你已经快到了,但这正是你需要做的。

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

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


0
投票

((上下文为?ContextWrapper)?.baseContext为?Activity)?.onBackPressed()

© www.soinside.com 2019 - 2024. All rights reserved.