Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Back button in custom View

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) -

app 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.

like image 839
Alexander Farber Avatar asked Dec 09 '22 01:12

Alexander Farber


1 Answers

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;
            }
        });
like image 194
vaibhav Avatar answered Dec 11 '22 12:12

vaibhav