简体   繁体   中英

How do I get back from a fragment to a previous fragment?

When working with java in Android Studio, how do I get back from a fragment to a previous fragment?

  1. To use the bottom tab, I am using fragments divided into three in MainActivity. I opened another fragment on that fragment to input information, but when I press Back on the phone, the application quits. How should I do it?

This is the code I added to MainActivity.

**public void onBackPressed() {
        List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
        for(Fragment fragment : fragmentList){
            if(fragment instanceof onBackPressedListener){
                ((onBackPressedListener)fragment).onBackPressed();
                return;
            }
        }
        if(System.currentTimeMillis() - lastTimeBackPressed < 1500){
            finish();
            return;
        }
        lastTimeBackPressed = System.currentTimeMillis();
        Toast.makeText(this,"Press the 'Back' button again to finish.",Toast.LENGTH_SHORT).show();
    }**
  1. And can the page that receives information from being entered in a different way than a fragment?

  2. Is it possible to delete the fragment while storing the input information after it is input from the fragment? When I go back, the stack is still piled up, so I keep seeing the previously entered information.

For the fragment you add that allows the user to input information, make sure to call:

fragmentTransaction.addToBackStack(null);

during the fragment transaction where you add the fragment.

Then get rid of the onBackPressed override, it's not necessary.

addToBackStack() will enable automatic handling of the BACK button press, removing the fragment transaction.

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