Reputation: 179
I'm trying everytime I press a key to launch a toast, but it seems its dosn't launching it, any idea?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txtKey);
editText = findViewById(R.id.etxtKeyboard);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_P:
Toast.makeText(this, "P pressed", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
Upvotes: 0
Views: 32
Reputation: 1143
As the Android documentation says about an Activity.onKeyUp()
method:
Called when a key was released and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.
So it seems that you are trying to catch onKeyUp() event when a focus in your findViewById(R.id.etxtKeyboard);
edit text view.
You can try add code like this in Activity.onCreate()
:
editText.setOnKeyListener(
new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_P:
Toast.makeText(MyActivity.this, "P pressed", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
}
);
Upvotes: 1