繁体   English   中英

如何动态添加视图到LinearLayout?

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

有没有办法在Android中动态添加图像并将其放置到线性布局中? 在php中,我只能回显图像标签并使用css对其进行定位,但不确定如何在android中解决此问题,因为xml似乎是非常严格的预定义。

您可以通过调用ViewGroup.addView(View)方法将视图添加到任何ViewGroup。 但是,这是添加视图的一种模糊方式。 最好是首先为给定的布局创建一个LayoutParams (考虑到视图),这将允许您更紧密地控制视图及其与父视图的关系。

这是将所有内容捆绑在一起的示例:

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);
    }
}

这是将视图动态添加到LinearLayout的方式。 但是,由于LinearLayout的结构和设计,实际上并没有太多的定位方式。 将LinearLayout视为一个在一个方向上充满视图的数组,您唯一可以做的就是更改它们在数组中的位置。 如果您想更好地控制View,建议您使用RelativeLayout。

暂无
暂无

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

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