简体   繁体   中英

go back to first fragment when press back

When I am in Fragment 5, for example, and I press the back button, the application comes out. What I want is when I press the Back button, I open Fragment No. 1. How can i do that?

I have tried many codes but it is not working, like

FragmentManager fm = getActivity().getSupportFragmentManager();
 for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
    fm.popBackStack();
}

and

getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Here is my fragment code in MainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // make new object and find the view "BottomNavigationView"
    BottomNavigationView navigationView = findViewById(R.id.bottom_navigation);
    // To make the first fragment shows when the app start.
    // We will ignore the "activity_main" and we will make new activity(fragment) called "fragment_home"
    // and we will add all views we want to display them on it.
    // (fragment_layout) it is a fragment have id was defined in "activity_main"
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout,
            new HomeFragment()).commit();
    // make Listener to call the fragments on buttons
    // to start new fragment
    navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            switch (item.getItemId()) {
                // first fragment "home"
                case R.id.home_item:
                    selectedFragment = new HomeFragment();
                    break;
                // second fragment "videos"
                case R.id.videos_item:
                    selectedFragment = new VideosFragment();
                    break;
                // third fragment "ebadat"
                case R.id.ebadat_item:
                    selectedFragment = new EbadatFragment();
                    break;
                // fourth fragment "images"
                case R.id.images_item:
                    selectedFragment = new ImagesFragment();
                    break;
                // fifth fragment "more"
                case R.id.settings_item:
                    selectedFragment = new MoreFragment();
                    break;
            }
            assert selectedFragment != null;
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, selectedFragment).commit();
            return true;
        }

    });
}

Add the onBackPressed Method:

@Override
public void onBackPressed() {
    //super.onBackPressed(); delete this line 
    // and start your fragment:

    NextFragment nextFrag= new NextFragment();
    getActivity().getSupportFragmentManager().beginTransaction()
         .replace(R.id.Layout_container, nextFrag, "findThisFragment")
         .addToBackStack(null)
         .commit();
}

First you have to implement the onBackPressed Method in your Fragment.

  1. create an interface with the name IOnBackPressed: click package -> new Java Class -> and choose interface in Kind -> OK your interface should look like this:

     public interface IOnBackPressed { boolean onBackPressed(); }
  2. after that you open your MainActivity and add this:

     @Override public void onBackPressed() { //super.onBackPressed(); delete this line // and start your fragment: Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (.(fragment instanceof IOnBackPressed) ||.((IOnBackPressed) fragment);onBackPressed()) { super.onBackPressed(); } }
  3. you implement this to your Fragment:

     public class Profil_Fragment extends Fragment implements IOnBackPressed

    and add this to the Fragment:

     @Override public boolean onBackPressed() { //do what you want NextFragment nextFrag= new NextFragment(); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, nextFrag, "findThisFragment").addToBackStack(null).commit(); return true; }

Add backstack and tag (you can use fragment name like "HomeFragment") for replacing fragment.

replace(fragmentId, fragment, fragmentName).addToBackStack(fragmentName)

And pop fragment like this

popBackStack(fragmentName,0)

Try adding transaction.addToBackStack(tag);

For example:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_layout, selectedFragment);
ft.addToBackStack( "tag" ).commit();

That will add your fragments to the backstack so the back button can work appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM