简体   繁体   English

如何动态添加视图到LinearLayout?

[英]How to add a View Dynamically to a LinearLayout?

Is there a way to dynamically add and position images into a linear layout in android? 有没有办法在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. 在php中,我只能回显图像标签并使用css对其进行定位,但不确定如何在android中解决此问题,因为xml似乎是非常严格的预定义。

You can add view to any ViewGroup by calling the ViewGroup.addView(View) method. 您可以通过调用ViewGroup.addView(View)方法将视图添加到任何ViewGroup。 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. 最好是首先为给定的布局创建一个LayoutParams (考虑到视图),这将允许您更紧密地控制视图及其与父视图的关系。

Here is a sample to tie everything together: 这是将所有内容捆绑在一起的示例:

class MyActivity extends Activity {
    @Override public void onCreate(Bundle icicle) {
        super.onCreate(icicle)

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        // Create 5 view to take up a small amount of space.

        View tmp = null;

        for (int i = 0; i < 5; i++) {
            tmp = new View(this);
            ll.addView(tmpnew LinearLayout.LayoutParams(
                50, // Width
                50);    // Height
            // Either or both the width and height may be ViewGroup.
            // (WRAP_CONTENT || FILL_PARENT || MATCH_PARENT)
        }

        setContentView(ll);
    }
}

This is how you would dynamically add a view to a LinearLayout. 这是将视图动态添加到LinearLayout的方式。 However, due to the structure and design of a LinearLayout, there really isn't much in the way of positioning. 但是,由于LinearLayout的结构和设计,实际上并没有太多的定位方式。 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. 将LinearLayout视为一个在一个方向上充满视图的数组,您唯一可以做的就是更改它们在数组中的位置。 If you want fine control over a View, I recommend a RelativeLayout. 如果您想更好地控制View,建议您使用RelativeLayout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM