我爲片段調用了setRetainInstance(true)。我在片段上添加了EditText和TextView。旋轉時,EditText中的文本仍然存在,但TextView中的文本消失了。爲什麼在調用setRetainInstance(true)時TextView的文本未被恢復?
我想我可以手動恢復TextView的文本,但我想知道爲什麼系統會自動恢復EditText的文本,而不是TextView。我做錯什麼了嗎?
重現步驟。
- 在EditText上
- 按類型的 「Android」 的實驗1按鈕。 TextView現在顯示「android」
- 旋轉設備。
結果
的EditText上有 「機器人」,但TextView的是空的。
MyFragment.java
public class MyFragment extends Fragment
{
private static final String TAG = "MyFragment";
EditText etInput;
Button btnTest1;
TextView tvMessage;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
Log.d(TAG, "onCreateView()");
View v= inflater.inflate(R.layout.my_fragment, container, false);
etInput = (EditText)v.findViewById(R.id.etInput);
btnTest1 = (Button)v.findViewById(R.id.btnTest1);
btnTest1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
tvMessage.setText(etInput.getText().toString());
Log.d(TAG, "btnTest1 was clicked");
}
});
tvMessage = (TextView) v.findViewById(R.id.tvMessage);
return v;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
{
String TAG = this.getClass().getName();
@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment mf = fm.findFragmentById(R.id.placeholder);
if(mf == null)
{
Log.d(TAG, "creating new my fragment");
mf = new MyFragment();
mf.setRetainInstance(true);
fm.beginTransaction().add(R.id.placeholder, mf).commit();
}
}
}
my_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tvMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnTest1"
android:text="Test 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:text="Fragment Test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@+id/placeholder"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
</FrameLayout>
</LinearLayout>
setRetainInstanceState將保留片段本身的狀態,而不是包含在該片段中的UI /視圖。爲此,您需要在片段中全局保存一些值,然後將視圖重置爲onCreateView中的這些值。 – zgc7009
我讀過的地方,如果你明確地定義在xml中的片段(與標籤),這將工作,但我不知道它是否可以幫助你 –
Pooya
然後,爲什麼EditText文本自動恢復? –