Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何以编程方式在相对布局中添加视图_Android - Fatal编程技术网

Android 如何以编程方式在相对布局中添加视图

Android 如何以编程方式在相对布局中添加视图,android,Android,我已经有了一个relative_layout.xml,它包含子布局。现在,我必须将布局添加到一个子相对布局insite中,relative\u layout.xml。您能告诉我如何通过编程实现它吗?首先通过代码创建视图,然后将其添加到所需的布局中 如果要将按钮添加到sub_布局中 RelativeLayout sub_layout = (RelativeLayout )findViewById(R.id.sub); Button yourButton = new Button(this);

我已经有了一个
relative_layout.xml
,它包含子布局。现在,我必须将布局添加到一个子相对布局insite中,
relative\u layout.xml
。您能告诉我如何通过编程实现它吗?

首先通过代码创建视图,然后将其添加到所需的布局中

如果要将按钮添加到sub_布局中

RelativeLayout sub_layout = (RelativeLayout )findViewById(R.id.sub);
Button yourButton = new Button(this);  
sub_layout.addView(yourButton);

RelativeLayout sub_layout1=(LinearLayout)findViewById(R.id.lyt_sub1)


子单元布局1.添加视图(新单元布局)

下面是一个例子,它将帮助您

        RelativeLayout child_layout = (RelativeLayout) findViewById(R.id.relative_layout_id);
        CheckBox cb = new CheckBox(getApplicationContext());
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                                         RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        child_layout.addView(cb, lp);
我所做的是使用findviewbyid获取相对布局,然后创建复选框。然后,我根据布局参数在相对布局上创建布局参数添加复选框。
希望对您有所帮助。

您的代码中有错误,请添加addView@IanWarwick谢谢你纠正我。谢谢,它工作得很好。但是我怎样才能改变这个布局的宽度和高度,比如说200dp*100dp。你说的是哪个布局,你在哪个布局上添加那个布局,或者其他的。。只需创建一个布局参数,并在其中指定RelativeLayout.LayoutParams.WRAP_内容,而不是指定长度和宽度。如果该布局已与其他父布局连接,则使用布局名称。SetLayoutParam(lp)将设置布局名称的长度和宽度。如果该视图未附加到任何位置或要添加的位置,请使用addView。