Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyListener not firing an event in Android

I have an Activity with one Fragment. This fragment has one button, and I want something to happen when I push the "enter" button on my hardware keyboard (I am testing it with adb keyevent).

I've read a lot of solutions here on stackoverflow, but none of them worked.

This is my fragment code:

btnPhoto = (Button) rootView.findViewById(R.id.taskBtnPhoto);
photoView = (ImageView) rootView.findViewById(R.id.taskPhotoView);

btnPhoto.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        takePhoto();
    }
});

btnPhoto.setFocusable(true);
btnPhoto.setFocusableInTouchMode(true);
btnPhoto.requestFocus();

btnPhoto.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (KeyEvent.KEYCODE_VOLUME_UP == keyCode) {
            doFoo();
            return true;
        }
        return false;
    }
});

This code is placed in the onCreateView part of my fragment. Using debug, the event is never fired when I launch KeyEvent from ADB or use the hardware keys of my phone (volume keys).

like image 499
Slash90ITA Avatar asked Jul 13 '15 11:07

Slash90ITA


1 Answers

public static class MyFragment extends Fragment {

        @Override
        public void onResume() {
            super.onResume();
            getView().setFocusableInTouchMode(true);
            getView().requestFocus();
            getView().setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    //YOUR CODE
                    return false;
                }
            });
        }
    }
like image 126
Tronum Avatar answered Nov 19 '22 14:11

Tronum