Recently in one of my apps re-design , I moved from all Activities to single activity architecture and converted all other activities to fragments.
So my app consists of a single activity which has TabHost (4 tabs) that contains fragments. In each tab fragment I am having multiple fragments (child fragments)
While going this route, I'm facing issues with back button navigation when using multi level fragments. How can I have a standard and consistent back button behaviour when going the single activity route?
Following is the code for back navigation for single child fragment:
private void catchBackEvent(View v) {
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isEnableFragmentBackStack()) {
getChildFragmentManager().popBackStack();
return true;
} else
return false;
}
return false;
}
});
}
public boolean isEnableFragmentBackStack() {
if (getChildFragmentManager().getBackStackEntryCount() > 0)
return true;
else
return false;
}
Also, I would like to know if the pros and cons of this approach and any potential roadblocks I might hit in the future.
__
We are supporting Android 4.1 and above, so we are using v4 support library.