如何使用LayoutInflator在运行时添加视图?

11

我有两个布局文件:main.xml 和 buttonpanel.xml。在 buttonpanel.xml 中,我将其中的 main linearlayout 的 gravity 设置为 bottom。现在我正在尝试使用以下代码添加 buttonpanel 布局。

setContentView(R.layout.main);
LinearLayout layout=(LinearLayout)findViewById(R.id.mainlinearlayout);
LayoutInflater inflater= (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.buttonpanel,null);
layout.addView(view);
我的问题是尽管我在buttonpanel.xml中将重力设置为底部,但面板仍添加到顶部。如果我使用include将buttonpanel.xml添加到main.xml中,则可以正常工作。能否有人帮我看看我的代码哪里出了问题?

请查看此链接以获取更详细的解释:https://dev59.com/hG445IYBdhLWcg3wH2vH - andig
可能是LayoutInflater的理解的重复问题。 - Bo Persson
2个回答

18

我在使用你所使用的方法膨胀视图时,遇到了布局参数被省略的问题。如果我使用稍微不同的 inflate 调用方式,我的布局参数就会被尊重:

parent_view = inflater.inflate(R.layout.buttonpanel, parent);

或者就像我的情况一样,当父视图不支持向其中添加视图时:

view = inflater.inflate(R.layout.buttonpanel, parent, false);

也许这个方法也能解决你的问题。

编辑:根据给定的参数,会返回不同的视图。 LayoutInflater


正如你所说,父视图不支持添加视图。因此,view = inflater.inflate(R.layout.buttonpanel, parent, false); 解决了我的问题。谢谢。 - Hitendra
也帮了我,但我必须调用parent.addView(view);将视图添加到布局中。 - Bojan Radivojevic
我用这种方法,但是我的视图仍然与顶部对齐 :/ - htafoya
不支持是什么意思?如何确定父级不支持addView? - Jongz Puangput

0

你可以使用childview index进行设置。我认为这会对你有所帮助。尝试另一种包括childindex的addview方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接