irene
irene

Reputation: 1

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.

Upvotes: 0

Views: 49

Answers (1)

CSmith
CSmith

Reputation: 13458

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.

Upvotes: 1

Related Questions