&autolink(id=main)
目次
参考にするリンク
Fragment.setRetainInstance(boolean)を使う。
Fragment.setRetainInstance(boolean)は、Fragmentにある機能の一つ。
説明をみると Activity#onRetainNonConfigurationInstance() から替わったメソッドの様子。
使い方。
呼ぶ位置は別にどこでもいいが、Fragmentのコンストラクタあたりで呼んでおけばいい。
すると自動的にFragmentで使用されているView.onSaveInstanceState()が呼び出さる。
あとはActivityが再起動した際に、自動的にFragmentの状態が復元される。
public class AutoRetainFragment extends Fragment implements OnClickListener {
public AutoRetainFragment() {
// ConfigurationChangeが起きた場合に復帰させる場合は true を指定。
setRetainInstance(true);
}
@Override
public View onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
) { View view
= inflater.
inflate(R.
layout.
auto_retain_fragment, container
); // ボタン押したら適当に初期値を変更する
view.findViewById(R.id.button1).setOnClickListener(this);
return view;
}
public void onClick
(View v
) { // 適当に初期値を変更する
TextView text = (TextView) getView().findViewById(R.id.textView1);
text.setText("onClick !!");
}
}
……残念なところは。
……と、これだけでいいように見せて実は足りない。
この設定を生かすにはView側にも指定が必要になるものもある。
この例では TextView がそれにあたる。
TextViewの場合は android:freezesText="true" を指定しておく必要がある。
しかもこの復帰処理、Activityが再起動してからチョイチョイ早い段階で発動するので注意が必要。
<?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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true" <!-- この指定がないと復元は自動で行わない -->
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
関連リンク
取得中です。
&trackback()
最終更新:2012年01月22日 04:44