Search code examples
androidactionlistenerkeylisteneronkeydown

key listener is not working for layout


i want to add onkeylistener to my linear layout but its not working, here is my code. thanks in advance.

 innerlayout.setOnKeyListener(new OnKeyListener() {

                @Override
                public boolean onKey(View v, int arg1, KeyEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getKeyCode()==KeyEvent.ACTION_DOWN){

                        Toast.makeText(HomeScreen.this, "down key is working", Toast.LENGTH_LONG).show();
                        innerlayout.setFocusable(true);
                    }
                    return true;
                }
            });

}

Solution

  • As touch events are passed from child to parent. if any child consumes the event (returns true), then it stops; it is not passed to the parent. Are you sure its not consumed elsewhere? Check this, true for one action, false for the rest and super call:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    super.onKeyDown(keyCode, event);
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
            //Toast here
                return true;
            }
            **return false;**
        }  
    

    Also, found:
    OnKeyListener or OnKeydown not work if children views take the focus
    onKeyDown not being called on key press on View
    Is this your case? what is the hierarchy of layouts