onKeyDown() issue

Deadly 提交于 2019-11-30 11:43:36

I found that I was returning true for all events, where I should only have been returning it for the code that I was using. I moved the return true inside the scope of the if statement and returned false otherwise That brought my menu back!

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    super.onKeyDown(keyCode, event);
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        dba.close();
        Intent result = new Intent("Complete");
        setResult(Activity.RESULT_OK, result);
        finish();
        return true;
    }
    return false;
}

I had a similar problem and solved it by adding

this.requestFocus();
this.setFocusableInTouchMode(true);

in the constructor of my SurfaceView subclass.

rrabio

i solved removing the if statement, like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch(keyCode)
    {
        case KeyEvent.KEYCODE_CAMERA:
            videoPreview.TakePicture();
            return true;
    }
    return super.onKeyDown(keyCode, event);
}
enam

I don't know why sometimes it does not work, though for one of my apps this keyDown() is working fine and again when I use it for a new app then it does not work.

But I have a solution which always works:

@Override
public boolean dispatchKeyEvent (KeyEvent event) {
    if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
        Toast.makeText(this, "Back button pressed", Toast.LENGTH_LONG).show();
        return true;
    }
    return false;
}
alaster

I solved this by adding into constructor this code:

setFocusable(true);
requestFocus();

thanks, Ciryon

Also every time I use setContentView(myView); I must call myView.requestFocus();. If there is a better solution please tell me.

Well, in looking at the API documentation the only thing that stands out is that the android:clickable attribute must be set as well as the view being enabled for the onKeyDown(...) method to work.

zhujian

you can try this

this.setFocusable(true);

Your Activity could be eating the key event. Override onKeyDown in the activity and throw a breakpoint in there.

Also: when you say you've "placed it in the main form" are you using the XML layout or doing in your code?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!