Reputation: 1658
On a Fragment, I have the following OnKeyListener. I use it to hide a View internal to that Fragment if its currently shown. If it is not shown, I don't consume the key press and Android does.
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
if (isSomeViewShowing) {
hideSomeView();
return true;
}
// Back pressed but view is not showing. Not consuming the event.
return false;
}
// Back not pressed. Not consuming the event.
return false;
}
});
It works well to hide the view and getting into the normal Fragment/Activity backstack when the view is not there, but it stops working if the user uses the soft keyboard to input text in an EditText and then hides the keyboard.
I know that the OnKeyListener doesn't work for soft keyboards, and that is OK for my needs. I just need the Listener to continue working after the input has finished and the keyboard is hidden.
Is there a way to prevent this to happen?
A workaround would be to listen for when keyboard is dismissed and add the OnKeyListener again when the keyboard is dismissed, but implementing this adds too much complexity for a simple task.
Upvotes: 3
Views: 749
Reputation: 2322
You could override onBackPressed()
in the activity
which is using the fragment
and them send a message to the fragment
to know that key back was pressed. Something like this:
Activity:
/**
* Triggered when the user press back button
*/
@Override
public void onBackPressed(){
mYourFragment.onBackPressed();
}
Fragment:
public void onBackPressed(){
if (isSomeViewShowing) {
hideSomeView();
}
}
Upvotes: 2