1

I have One Activity

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activities.Dashboard.MainActivity">
        <FrameLayout
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
</RelativeLayout>

And I have 10 Fragments i show them in main_container Frame Layout How can i write code to go back to last fragment This is my Activity code :

public class MainActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        fragmentManager = getSupportFragmentManager();
        fragment = new HomeFragment(); 
        final FragmentTransaction transaction = 
        fragmentManager.beginTransaction();
        transaction.replace(R.id.main_container, fragment).commit();
  }
}

In Home Fragment :

public class HomeFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.bottom_bar_home, container, false);
        fragmentManager = getActivity().getSupportFragmentManager();
         // ...... etc

        return view;
    }

}

and all fragments the same code with another data.

2 Answers2

1

It worked to me by this code : I put in Base Activity :

 @Override
    public void onBackPressed() {
        int count = getFragmentManager().getBackStackEntryCount();
        if (count == 0) {
            super.onBackPressed();
        } else {
            getFragmentManager().popBackStack();
        }
    } 

And every call for fragment i put AddtoBackStack(null) :

  fragment = new yourFragment();
  final FragmentTransaction transaction = fragmentManager.beginTransaction();
  transaction.replace(R.id.main_container, 
  fragment).addToBackStack(null).commit();
0

Try this:

    if( getFragmentManager().getBackStackEntryCount() > 0) { 
    getFragmentManager().popBackStack(); 
return; 
    } 
super.onBackPressed();

You should read this related question as well:

Community
  • 1
  • 1
esQmo_
  • 1,464
  • 3
  • 18
  • 43