3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

動的にxmlレイアウトを追加する。

Posted at

久しぶりに使ったら軽くハマったので備忘録

このエラーに軽く悩んだ
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.my_layout);
LinearLayout v = (LinearLayout)getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);

for (int i = 0; i < 10; i++) {
   linearLayout.addView(v);
}

と書いていたのだがこれだと「v」が一回目のforの中で親のレイアウトの管理下になるため、
2回目の繰り返しでエラーになる。

なのでforの中でvを都度定義した。

LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.my_layout);
for (int i = 0; i < 10; i++) {
   LinearLayout v = (LinearLayout)getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
   linearLayout.addView(v);
}

これで多分おk!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?