縦横切り替えなどのConfigurationChangeで自動的にFragmentを復元させる

&autolink(id=main)

目次


参考にするリンク


Fragment.setRetainInstance(boolean)を使う。

Fragment.setRetainInstance(boolean)は、Fragmentにある機能の一つ。
説明をみると Activity#onRetainNonConfigurationInstance() から替わったメソッドの様子。

使い方。

呼ぶ位置は別にどこでもいいが、Fragmentのコンストラクタあたりで呼んでおけばいい。
すると自動的にFragmentで使用されているView.onSaveInstanceState()が呼び出さる。
あとはActivityが再起動した際に、自動的にFragmentの状態が復元される。

  1. public class AutoRetainFragment extends Fragment implements OnClickListener {
  2.  
  3. public AutoRetainFragment() {
  4. // ConfigurationChangeが起きた場合に復帰させる場合は true を指定。
  5. setRetainInstance(true);
  6. }
  7.  
  8. @Override
  9. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  10. View view = inflater.inflate(R.layout.auto_retain_fragment, container);
  11. // ボタン押したら適当に初期値を変更する
  12. view.findViewById(R.id.button1).setOnClickListener(this);
  13. return view;
  14. }
  15.  
  16. public void onClick(View v) {
  17. // 適当に初期値を変更する
  18. TextView text = (TextView) getView().findViewById(R.id.textView1);
  19. text.setText("onClick !!");
  20. }
  21. }

……残念なところは。

……と、これだけでいいように見せて実は足りない。
この設定を生かすには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