Android使用布局作为模板创建多个布局实例
好的,我了解如何使用 include 标签,但遇到了问题。
基本上我想要一个在 xml 中定义的布局,其中有几个 TextView
和一个 ImageView
。然后,我想要迭代数组并根据数组中的内容(在运行时填充)填充 xml 布局中的字段。从而制作 xml 布局的多个副本并使用唯一数据填充字段。现在我不知道如何以这种方式重用这个 LinearLayout
,因为其中的 TextView
和 ImageView
有一个常量 id,我需要制作此布局的多个副本。
有没有什么方法可以膨胀资源然后制作它的副本,这会起作用......所以
LinearLayout one = new LinearLayout(inflater.inflate(R.layout.home, container, false));
^不幸的是没有这样的构造函数。
唯一的其他方法是以编程方式完成这一切,但我更愿意在 xml 中而不是在代码中拥有视图和 LinearLayout 的属性。就像我希望 LinearLayout 成为一个模板,我猜你可以复制它......真的不确定这是否可能。
OK, So I understand how to use the include tag but I've run into a problem.
Basically I want to have a layout defined in xml which has a couple of TextView
s and an ImageView
in it. I then want to iterate across an array and populate fields within the xml layout depending on whats in an array(which is populated on runtime). Thus making multiple copies of the xml layout and populating the fields with unique data. Now i've got no idea how you can re-use this LinearLayout
in this way as the TextView
s and ImageView
s within it have a constant id and I need to make multiple copies of this layout.
Is there any way to inflate a resource and then make a copy of it, that would work... So
LinearLayout one = new LinearLayout(inflater.inflate(R.layout.home, container, false));
^ There is no constructor like that unfortunately.
The only other way is to do it all programatically but I would of preferred to have the properties of the views and the LinearLayout
in xml rather than in the code. It's like I want the LinearLayout
to be a template which you can make copies of I guess... Really not sure if that's possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以轻松做到这一点,只需将其分解即可。首先,加载要插入动态视图的布局。然后,您可以膨胀子视图并根据需要多次填充它。然后将视图添加到父布局中,最后将活动的内容视图设置为父视图。
这是一个示例:
这是我要插入的 main.xml 文件:
这是我膨胀、填充和动态插入的 custom.xml 视图:
You can easily do this, you just have to break it down. First you load the layout that you want to insert your dynamic views into. Then you inflate your subview and populate it as many times as you need. Then you add the view to your parent layout, and finally set the content view of the activity to the parent view.
Here's an example:
here is the main.xml file that I am inserting into:
and here is the custom.xml view that I inflate, populate and dynamically insert:
对于仍在寻找类似解决方案的任何人,显然您也可以直接在 xml 中使用
include
并且仍然能够在代码中引用它们:来源:罗曼·盖伊
To annyone still looking for a similar solution, apparently you can also use
include
directly in xml and still be able to refer to them in code:Source: Romain Guy