如何动态添加视图到LinearLayout?
有没有办法在 android 中动态添加图像并将其定位到线性布局中?在 php 中,我可以只回显图像标签并使用 css 来定位它,不太确定如何在 android 中解决这个问题,但是因为 xml 似乎是非常严格预定义的。
Is there a way to dynamically add and position images into a linear layout in android? in php I could just echo out an image tag and use css to position it, not really sure how to tackle this in android however as the xml seems to be very rigidly predefined.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过调用 ViewGroup.addView(View) 方法。
然而,这是一种模糊的添加视图的方式。首选的是,您首先为给定创建一个 LayoutParams布局(考虑到视图)这将允许您更密切地控制视图及其与其父视图的关系。
下面是一个将所有内容联系在一起的示例:
这就是动态地将视图添加到 LinearLayout 的方法。然而,由于 LinearLayout 的结构和设计,实际上没有太多的定位方式。将 LinearLayout 视为一个在一个方向上充满视图的数组,您唯一能做的就是更改它们在数组中的位置。如果您想对视图进行精细控制,我推荐 RelativeLayout。
You can add view to any ViewGroup by calling the ViewGroup.addView(View) method.
How ever, this is kind of a vague way of adding a View. What is preferred is that you first create a LayoutParams for the given layout (with the view in mind) This will allow you to control the view and its relationship with its parent view more intimately.
Here is a sample to tie everything together:
This is how you would dynamically add a view to a LinearLayout. However, due to the structure and design of a LinearLayout, there really isn't much in the way of positioning. Think of a LinearLayout as an array full of views in one direction, the only thing you can do is change where they are in the array. If you want fine control over a View, I recommend a RelativeLayout.