3

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.

Handroid
  • 399
  • 1
  • 2
  • 13

1 Answers1

0

You can also use onBackPressed it probably is going to be cleaner and for sure will be maintained by Google. Also, as you said in the end, the v4 suport library actually is for API 4, which is for Android 1.6... if your target is Android 4+ you will be good without support library.

Pozzo Apps
  • 1,859
  • 2
  • 22
  • 32