开发者

Inflated layout behaves differently than static XML layout

I have a layout that I am using as a parent layout template. Depending on what Activity I launch, I would like to populate the contents of a LinearLayout in the parent template with an inflated view. Now, if I place the parent and child layouts in开发者_Python百科to the same XML file, things look good. But if I use setContentView() on the parent layout, and then inflate the child view and add it to the same place in the parent layout, things don't work. Both the LinearLayout that I am putting the child view into, and the LinearLayout that is the root of the child view have android:layout_height="fill_parent", but the child view is unable to fill the LinearLayout that it is added to.

Is there something obvious I'm not doing correctly? Remember, these layouts should look identical, just one method is static, and the other is dynamic. I assume that this has something to do with the parent layout dimensions being calculated and not updated after the child view is inflated.

Thanks!


OK, I figured this out.

You need to pass the child's parent view into the inflater when you are inflating the child so that the inflater knows how big to make it. I was inflating with a null parent and then adding the child to the parent, but that resulted in the child behaving as if I set the layout params to "wrap_content".

Incorrect:

ViewGroup parent = (ViewGroup) root.findViewById(R.id.parent);
parent.removeAllViews();
LinearLayout child;
child = (LinearLayout) inflater.inflate(R.layout.child, null);
parent.addView(child);

Correct:

ViewGroup parent = (ViewGroup) root.findViewById(R.id.parent);
parent.removeAllViews();
(LinearLayout) inflater.inflate(R.layout.child, parent);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜