In a word game for Android with DrawerLayout the left and right navigation drawers are closed by the following code in the MainActivity:
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(mLeftDrawer)) {
mDrawerLayout.closeDrawer(mLeftDrawer);
} else if (mDrawerLayout.isDrawerOpen(mRightDrawer)) {
mDrawerLayout.closeDrawer(mRightDrawer);
} else {
super.onBackPressed();
}
}
This works well (the left screenshot) -
However I am also trying to detect Back button press in my custom View (which overrides onDraw
method to draw scrollable game board and letter tiles) by the following methods - (to allow app user cancelling tile swapping or recalling unplayed tiles from the game board) - but none of them is called:
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (mSwapping && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
cancelSwapLetters();
return true;
}
return super.dispatchKeyEventPreIme(event);
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (mSwapping && keyCode == KeyEvent.KEYCODE_BACK) {
cancelSwapLetters();
return true;
}
return super.onKeyPreIme(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mSwapping && keyCode == KeyEvent.KEYCODE_BACK) {
cancelSwapLetters();
return true;
}
return super.onKeyDown(keyCode, event);
}
I have put breakpoints in the above methods, but none of them are hit.
Please advise me, how to solve this problem.
This code helped me get back press event in a fragment try this code :
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().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 handled back press) return true;
else return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With