本文介绍了如何将视图动态添加到已在 xml 布局中声明的 RelativeLayout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 xml 布局文件中声明了一个 RelativeLayout
.现在我想将 Views
从代码添加到现有布局.我通过代码向这个现有布局动态添加了一个 Button
,如下所示:
I declared a RelativeLayout
in a xml layout file. Now I want to add Views
from code to the existing Layout. I added a Button
dynamically to this existing layout as below through code:
rLayout = (RelativeLayout)findViewById(R.id.rlayout);
LayoutParams lprams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Button tv1 = new Button(this);
tv1.setText("Hello");
tv1.setLayoutParams(lprams);
tv1.setId(1);
rLayout.addView(tv1);
现在我需要在已添加的 Button
的右侧添加另一个 Button
.我找不到在先前添加的按钮右侧添加新按钮的方法.
Now I need to add another Button
to the right of the already added Button
. I am not able to find the way in which I can add the new one to the right of the previously added button.
推荐答案
为第二个添加的Button
LayoutParams
添加规则RelativeLayout.RIGHT_OF
:
Add the rule RelativeLayout.RIGHT_OF
for the second added Button
LayoutParams
:
// first Button
RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.rlayout);
RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Button tv1 = new Button(this);
tv1.setText("Hello");
tv1.setLayoutParams(lprams);
tv1.setId(1);
rLayout.addView(tv1);
// second Button
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Button tv2 = new Button(this);
tv1.setText("Hello2");
newParams.addRule(RelativeLayout.RIGHT_OF, 1);
tv2.setLayoutParams(newParams);
tv2.setId(2);
rLayout.addView(tv2);
这篇关于如何将视图动态添加到已在 xml 布局中声明的 RelativeLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!