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).
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;
}
});
}
}
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