I have an Activity and many fragments inflated in same FrameLayout
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
example: mainActivity > any fragment (press back button) > activity is blank.
In onCreate:
layout = (FrameLayout)findViewById(R.id.content_frame);
layout.setVisibility(View.GONE);
When I start a fragment:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, profileFragment);
ft.addToBackStack(null);
ft.commit();
layout.setVisibility(View.VISIBLE);
I suppose I need to make the frameLayout's visibility GONE
again on back pressed, but how do I do this?
I tried onBackPressed
and set layout.setVisibility(View.GONE);
but I cannot go back through fragments, as I go directly to main page.
To add a fragment
If you have more than one fragment been used in the activity or even if you have only one fragment then the first fragment should not have addToBackStack defined. Since this allows back navigation and prior to this fragment the empty activity layout will be displayed.
But for the other fragment you need to have this defined otherwise the back will not navigate to earlier screen (fragment) instead the application might shutdown.
Sorry for the late response.
You don't have to add ft.addToBackStack(null); while adding first fragment.
You can override
onBackPressed
and check to see if there is anything on the backstack.On a recent personal project, I solved this by not calling
addToBackStack
if the stack is empty.Here's my full implementation:
If you want to track by the fragments you should override the
onBackPressed
method, like this