i have a problem with onkeylistener event, my code is like this
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.pnt_articulo);
imbAgregarArt = (ImageButton)findViewById(R.id.imbAgregarArt);
imbAgregarArt.setOnKeyListener(key);
}
OnKeyListener key = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN) {
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
};
i use the debug to stop in Toast line don’t enter
Please help
What you’re doing is listening for key events, meaning keyboard presses and such, and for that purpose your code is perfectly fine. Make sure the
ImageButtonis selected and press any key and yourToastwill appear.Since this is a very odd behaviour, you’re probably after an
OnClickListener:Note that we’ve changed the
OnKeyListenerto anOnClickListener, the first one listens to keyboard activity while the second one listens to user interaction with the objects by clicking on them, either with the finger (press) or selecting with a trackpad or whatever the device can do.As a sido note
If you’re curious about why the other one wasn’t working even if you pressed a keyboard key, the problem came from the fact that the view wasn’t focused. For a view to listen to keyboard events inside of it, they first need to be selected, this sounds logical right?