如何以编程方式添加视图来查看 [英] How to Programmatically Add Views to Views

查看:97
本文介绍了如何以编程方式添加视图来查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个的LinearLayout,我想一个视图添加到它,从Java的code我的计划。用什么方法用于此?我不要求它是如何在XML中完成的,这是我所知道的,而是,我该怎么办沿着这行的东西?

Let's say I have a LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I'm not asking how it's done in XML, which I do know, but rather, how can I do something along the lines of this?

(一查看)。新增(别论)

(One View).add(Another View)

就像可以在Swing做。

Like one can do in Swing.

推荐答案

调用 addView 是正确的答案,但你需要做的比这多一点得到它工作

Calling addView is the correct answer, but you need to do a little more than that to get it to work.

如果您通过构造函数创建一个视图(例如,按钮myButton的=新的Button(); ),你就需要调用 setLayoutParams 在新建成的观点,传递父视图的的LayoutParams内部类的一个实例,你添加新建成的孩子到父视图之前。

If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

例如,您可能有以下code在的onCreate()函数假设你的LinearLayout已经ID R.id.main

For example, you might have the following code in your onCreate() function assuming your LinearLayout has id R.id.main:

LinearLayout myLayout = findViewById(R.id.main);

Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.FILL_PARENT,
                                     LinearLayout.LayoutParams.FILL_PARENT));

myLayout.addView(myButton);

确保设定的LayoutParams是很重要的。每个视图至少需要一个layout_width和layout_height参数。同时得到正确的内​​部类是很重要的。我用得到浏览加入的TableRow正常显示,直到我想通了,我是不及格TableRow.LayoutParams的实例子视图的setLayoutParams挣扎着。

Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.

这篇关于如何以编程方式添加视图来查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆