In my first fragment I have an EditText
with a value. The problem is when I go to FragmentTwo
and go back to FragmentOne
the EditText
(in FragmentOne
) loses the text I previous inserted. I tried to save it in the onSaveInstanceState()
and retrieve in the onViewStateRestored()
but it seems that he does not store the information because the onSaveInstanceState()
is never called and the savedInstanceState
is always null.
This is my fragment replacing method
fragmentManager
?.beginTransaction()
?.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_out_right, R.anim.slide_in_right)
?.replace(frame, MyFragment.newInstance(), tag)
?.addToBackStack(tag)
?.commit()
This is my onSaveInstanceState()
in FragmentOne
:
override fun onSaveInstanceState(outState: Bundle) {
outState.putDouble(Constants.currentAmount, currentAmount)
super.onSaveInstanceState(outState)
}
This is my onViewRestored in FragmentOne
:
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
if(savedInstanceState!= null) {
currentAmountSaved = savedInstanceState.getDouble(Constants.currentAmount)
}
}
This is my back press in FragmentTwo
:
fragmentManager?.popBackStack()
So my goal is to save the EditText
, pass to FragmentTwo
, and when I go back to FragmentOne
the same EditText
is with the value I put when I change Fragments
.
This is my xml file from the FragmentOne
(The fragment I want to restore)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<View
android:id="@+id/fManageFundsHeaderLayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@color/colorBackgroundToolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<include
android:id="@+id/addFundsComponent"
layout="@layout/component_manage_funds"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/fManageFundsHeaderLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>