This post explains how to handle hardware back button in a Fragment OR DialogFragment.
In DialogFragment, it’s quiet straight forward to achieve this. You’ve to get the dialog instance and set onKeyListener on it :
if (getDialog() != null) {
getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
Timber.i("hardware back button pressed");
}
}
});
}
This can be done in the onViewCreated callback.For fragments, this method doesn’t work and fragments doesn’t have a direct callback to catch this event. So in this case, the approach that we follow is :
You have to catch this event in activity’s
onBackPressed method and then call a method on your fragment that handles this, something like :@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tagWithWhichYouAddedIt);
if (fragment.handlebackPress()) { // and then you define a method handlebackPress with the logic to handle back press or not
// decide how you want to proceed
}
}
Note that you’ll find some references on internet which ask you to set
KeyListener on fragment’s parent view, but that doesn’t work.Let me know in case of any doubts.
Cheers !
Great write-up! 👏 You’ve explained the inner workings of MaterialShowcaseView in a very clear and structured way, especially the breakdown of the PorterDuff masking process and how the library attaches to the window decor view and overrides onDraw()—that really helps developers understand what’s happening under the hood. I also liked how you covered the logic behind positioning the content box above or below the highlighted view, since layout calculations are often the trickiest part when modifying such libraries. It’s impressive that you didn’t just use the library but actually explored and customized it to fit your needs—much like how premium UI components such as Luxury Doors are used in high-end design projects, where true value comes from understanding the structure and tailoring it precisely. Looking forward to the next part and the additional functionalities you’ve added! 🚀
ReplyDelete