Back button in an Activity without recreate previo

2020-07-21 05:08发布

I have a master activity that is a menu (A). The activity A have 6 fragments. One of them is a gallery of pictures (Figure 1). When you touch a picture you go to the picture details activity (B) (Figure 2). I add the tag "parentName" to the activity B in the AndroidManifest.xml. So the parent of the activity B is the activity A. The problem is: when you are in activity B and you press the Up Button (Figure 2) the activity A is recreated and it shows the first fragment of the activity A (not the gallery fragment). I want the same behavior of the Instragram app when you back to a previous activity. It seems like the Instagram app don't recreate the previous activity. The expected behavior is also similar to the behavior of the back button (Figure 3). How can I achieve this behavior? Thanks

Figure 1. Master Activity with Gallery fragment Figure 1. Picture details Activity

Figure 2. Picture details Activity Figure 2. Picture details Activity

Figure 3. Back button Figure 3. Back button

2条回答
放荡不羁爱自由
2楼-- · 2020-07-21 05:37

May be programatically you are using this :

getFragmentManager().beginTransaction().replace(R.id.content_frame, new FragmentB(),null).addToBackStack(null).commit();

Replace it with this line :

getFragmentManager().beginTransaction().add(R.id.content_frame, fragment,null).addToBackStack(null).commit();
查看更多
趁早两清
3楼-- · 2020-07-21 05:54

I've solved my problem easily. I just had to add the tag android:launchMode="singleTop" to the activity A. I also add the next code in the activity A but probably isn't necessary. I hope you find it useful.

@Override
protected void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
    super.onRestoreInstanceState(savedInstanceState);
}
查看更多
登录 后发表回答