TabUIの中にFragment、そのFragmentの中にbuttonとEditTextとListFragmentという構造のものを作ろうとしている時にInflateExceptionが出て大変だったのでメモ。
1回めの表示は問題ないのだが他タブを見てからそのタブに戻ろうとしたらInflateExceptionで死ぬ。
変更前
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/SampleEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/queryHint"
android:maxLines="1" >
</EditText>
<Button
android:id="@+id/SampleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/Load" >
</Button>
<fragment
android:id="@+id/list"
android:name="com.Android.test.TestListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Fragmentを静的に置いてた。
この場合親がActivityとかだったら平気なんだけど親もFragmentなのでネストしたFragment となる。
ネストしたFragmentはサポートされるようになったが静的には生成出来ない。
必ず動的にしなければならないようだ。
NestedFragment
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.
ということで変更
変更後
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/SampleEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/queryHint"
android:maxLines="1" >
</EditText>
<Button
android:id="@+id/SampleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/Load" >
</Button>
<LinearLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>/
</LinearLayout>
そしてFragment側で動的に呼び出す。
public class SampleFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sample_fragment, container, false);
}
@Override
public void onStart() {
super.onStart();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.list_container, new TestListFragment()).commit();
}
}
呼び出す場所は適当にonStart()にしてるけどライフサイクル的にダメかもしれない...
多分当たり前なことなんですよねぇ...1回めは表示出来てしまったのでハマってしまった。
静的に呼び出すとIDだかタグが固定されちゃって2回め呼び出した時に重複して死ぬとかなんとか。
割りとハマったのでメモ代わりに。