如何通过仅膨胀一次来将相同的视图多次添加到父级
我有一个以垂直方向作为父级的 LinearLayout,我想以编程方式多次向该父级添加一些视图。现在,每次在添加到父元素之前获得对每个 UI 元素的新引用时,我都会对子元素进行膨胀。这似乎不是很有效,有没有更好的方法来做到这一点。
我正在使用的当前代码如下,如果我在 for 循环之前仅膨胀一次,我会收到运行时错误“他指定的子级已经有父级。您必须首先在子级的父级上调用removeView()。”
LayoutInflater inflator = LayoutInflater.from(getBaseContext());
LinearLayout parentPanel = findViewById(R.id.parent_pannel);
ArrayList<String> myList = getData();
for(String data : myList) {
// inflate child
View item = inflator.inflate(R.layout.list_item, null);
// initialize review UI
TextView dataText = (TextView) item.findViewById(R.id.data);
// set data
dataText.setText(data);
// add child
parentPanel.addView(item);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你真的检查过充气是否缓慢吗?据我所知,膨胀视图非常快(几乎与手动创建视图一样快)。
您可能会感到惊讶,但实际上 inflate 根本不解析 XML。用于布局的 XML 在编译时被解析和预处理 - 它们以二进制形式存储,这使得视图膨胀非常有效(这就是为什么您不能从运行时生成的 XML 来膨胀视图)。
Did you actually check if inflate is slow? As far as I know, inflating view is very fast (almost as fast as creating views manually).
It might be surprising for you to hear but inflate in fact does not parse the XMLs at all. XMLs for layout are parsed and pre-processed at compile time - they are stored in a binary form which makes view inflation very efficient (that's why you cannot inflate a view from an XML generated at runtime).
我不确定你的观点是什么,但你是否手动创建它而不是膨胀 XML:
但是,是的,你显然正在尝试使用 简单的 ListView & API
I'm not sure what your view is but have you creating it manually over inflating the XML:
But yeah your clearly attempting something that has been done for you with Simple ListView & API
你不能,即使你尝试从旧的
视图
对象创建一个新视图
,该对象也将通过引用而不是值传递,因此,您将得到一个 Exception 作为 childAlreadyHasParent,因此,唯一的方法是将view
放入for 循环中
与您想要的次数膨胀,并且这个循环必须包含从一开始的创建过程,而不仅仅是膨胀线。You can't, even if you try to create a
new view
from the oldview
object the object will be passed by reference not value, and hence you will got an Exception as the childAlreadyHasParent, and so, the only way is to put theview
into afor loop
with the number of times you want it to be inflated, and this loop must contain the creating process from beginning not only the inflating lines.多次充气不能像单次充气那样进行。希望这会起作用
这会起作用,至少对我有用
Inflating multiple times cannot be done the same way doing it in single shot. Hope this works
This will work, at the least worked me