Reputation: 7038
Following my previous post where I asked about implementing parceable objects, the solution I got was to use setRetainInstance(true);
method.
@CommonsWare provided me a sample which I modified as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="387dp"
android:layout_height="103dp"
android:text="New Text"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="@+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
RotationFragmentDemo.java
package com.rotationfragment;
import android.app.Activity;
import android.os.Bundle;
public class RotationFragmentDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This check returns 'null' for the first time when there are no fragments
if (getFragmentManager().findFragmentById(android.R.id.content) == null) {
getFragmentManager().beginTransaction().add(android.R.id.content, new RotationFragment()).commit();
}
}
}
RotationFragment.java
package com.rotationfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RotationFragment extends Fragment implements
View.OnClickListener {
TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// This should help to retain fragment
setRetainInstance(true);
View result=inflater.inflate(R.layout.activity_main, parent, false);
result.findViewById(R.id.button).setOnClickListener(this);
textView = (TextView)result.findViewById(R.id.textView);
return(result);
}
@Override
public void onClick(View v) {
textView.setText("Hello.");
}
}
Upon rotation the text in TextView
is not restored.
I know some of you would suggest using parceable writeString
parceable method to fix this simple example but I want to know why is the Fragment not retained here using setRetainInstance(true)
?
And I don't need to retain a string but Socket
, Thread
and Activity
as in previous post.
Upvotes: 0
Views: 391
Reputation: 2009
See the answer, "onRetainInstance saves the Fragment object, but I still have to rebuild UI in onCreateView", So you have to restore the state of your views manually
Upvotes: 2