简体   繁体   中英

How to navigate to previous fragment of previous activity

I have a main activity A with 4 fragments on top of it. The fragments appear one after the other on button click.

After I click button on last fragment (fourth), I am taken to a new activity B.

How can I implement back button press as such when user clicks on it. He is taken to the fourth fragment of Activity A?

You need to use the back stack for this. Each time you add a change fragments you will want to add that fragment to the back stack.

//Create an instance of your fragment;
MyFragment frag = MyFragment.newInstance();
//replace the fragment in a normal fragment transaction
getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, frag, "MyFragment Tag")
                //add to the back stack 
                .addToBackStack(f)
                .commit();

The thing about this, is now the back button will traverse through each of your previous fragments. So after hitting fragment 3, if you hit the back button, you will see fragment 2, etc.

This may not be your desired result, so you may only want to add a the fragment to the back stack when you add fragment 4.

You can pass data from the activity B to the activity A, inside onBackPressed function

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent i = new Intent(getApplicationContext(), AcvityA.class);
    i.putExtra("position","4");
    startActivity(i);

}

In your activity A

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String position = extras.getString("position");
    //load the fragment based in position 
}

Hope this help. Regards

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