Saving Android Activity Status

In the main action, ActivityAI replace the FragmentAfragment FragmentB. From the FragmentBuser can start a new activity ActivityB. By clicking the back button in ActivityB, it will be displayed ActivityAwith an image FragmentA. I expected to see FragmentBwith his last state. Do I have to keep the state of previous actions separate to ensure this behavior?

ActivityA(FragmentA) -> ActivityA(FragmentB) -> ActivityB 
BACK
ActivityA(FragmentB)

In the main action, I set the current fragment using:

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
               .replace(R.id.a_main_frame_content, new FragmentB())
               .addToBackStack(null)
               .commit();

From the snippet, I start a new action using:

Intent intent = new Intent(getActivity(), ActivityB.class);
getActivity().startActivity(intent);

ActivityAset as parent activity ActivityBto ensure proper navigation.

[UPDTATE] , , . , , - .

+4
3

:

parentActivity ( , parentActivity , , , setIntent):

    currentActivityIntent.putExtra("random-unique-key-for-each-activity",
random-unique-key-for-each-activity);

, , :

myKeyIntentMap.put(random-unique-key-for-each-activity, currentActivityIntent);

, "":

{
String parentKey = currentActivity.parentActivity.getIntent.getStringExtra("random-unique-key-for-each-activity");
Intent intentToLaunch = (Intent)myKeyIntentMap.get(parentKey);
intentToLaunch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP );
startActivity(intentToLaunch);
}

, , - A-someAct1-someAct2-B, , A, " ", .

P.S. , .

+3

"" . , . , "" Activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        onBackPressed();
    }
    return true;
}
+3

, , ActivityB, A , , ActivityA ActivityA , . sharedPfer. , onCreateView(), . , .

public static final String PREFS_NAME = "mypref";
boolean isVisited;
//check sharedpref
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
 isVisited= settings.getBoolean("isVisited", false);

if(!isVisited){
// set fragmentA
}else{ 
// set fragmentB
}


// inside fragment transaction block

Editor edit = settings.editor();
isVisited.setBoolean(true);
edit.commit();
+2

Source: https://habr.com/ru/post/1524682/


All Articles