简体   繁体   中英

Android back button - how to preserve parent state when navigating to and back from next activity

Activity A has a list of categories (RecyclerView) in a fragment. When clicking on an item, a new Activity B is launched, which also contains a list of items (RecyclerView) in a fragment, via an adapter: `

    myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Intent dynamicCableView = new Intent(view.getContext(), CableOverview.class);
           dynamicItemView.putExtra("systemModel", systemModelList.get(position));
           view.getContext().startActivity(dynamicItemView);
        }`

Clicking on one of those, Activity C, containing data pertaining to that item, is launched, basically like this:

public void goToAnActivity(View view) {
Intent Intent = new Intent(this, AnActivity.class);
startActivity(Intent);
}

When returning from Activity C via the back button to its parent Activity B, the previous state is not stored, so the list of items is gone whereas in my understanding, it should be retrieved from the stack. Instead onDestroy of B (NOT only of C) is called. I do NOT want to preserve data from Activity C but go back to its parent which should maintain its state. It basically should remember which category was selected to display its subset of items. I am using API 25.

I tried: overriding onSaveInstanceState in the fragment of B or in the activity. Doing away with the fragments and putting the lists in the activity itself. However, savedInstanceState is always null when navigating back.

How do I ensure my list can be recreated?

EDIT: Manifest contains:

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.Launcher">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

I found the solution when realizing that the problem actually was OnDestroy always getting called when navigating back. Thanks to @gokhan, I knew it was related to the launch mode. According to this answer, Activity B requires this line in the manifest: android:launchMode="singleTop"

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