简体   繁体   中英

Restore activity with the right fragment and state

I have an application with a main menu that when clicked, navigate to different activities.

One of these activities its a Search, with container that i update with many fragments. Its a kind of search, with 3 steps. (Step 1, Step 2, Step 3)

When i go for other activity and back to the Search Activity, the state is lost.

Whats is the best way to restore the activity with the right fragment ?

I have tried android:launchMode="singleInstance" and also intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_CLEAR_TOP) to force one instance of activity, and actually works but is taking time to open the activity for the first time (the app kind of stop works and then start again)

I think i can't just use savedInstanceState() because, each fragment need some information chosen on the previous fragment

Any suggestion ?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Top bar Menu-->
    <include  layout="@layout/partials_top_bar"/>


    <FrameLayout
        android:windowSoftInputMode="adjustNothing"
        android:id="@+id/container"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </FrameLayout>


    <!--Bottom Bar Menu-->
    <include  layout="@layout/partials_bottom_bar"/>

</LinearLayout>

When the user choose some action, them i update the actual fragment with

        activity.supportFragmentManager
                .beginTransaction()
                .replace(R.id.container, fragment)
                .addToBackStack(null)
                .commit()

EDIT: Found a solution. The "delay" / App freeze showed when i open SingleInstance was caused by removing the transition animation of all activities. But only the single instance activity presents this delay. So i'm gonna use this. Thank you so much guys.

You can create a static variable "state" in your activity, could be String, and when you change Fragment, you change de variable value, for example, when you change to the StepOneFragment you put the value to "step_one", StepTwoFragment -> "step_two", StepThreeFragment -> "step_three", and if you get back you change the variable value depending in what fragment are you on, then in onCreate of SearchActivity, you make a switch in that variable, and depending of the value, you load the desired Fragment.

Hope it helps

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