如何在另一个视图下添加动态按钮?
问题描述:
在Android中,我有一个代码块:如何在另一个视图下添加动态按钮?
// RelativeLayout with id is "root": main.xml
<EditText
android:id="@+id/pref_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:hint="Text to share in preference"
/>
// This is the button I want to add to main.xml
<Button
android:id="@+id/save_button"
android:layout_below="@id/pref_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
/>
在我的活动,随着RelativeLayout.LayoutParam
我可以在位置root
鉴于left, right, top, bottom
添加button
,但我不能添加below
或等...另一种观点! 那么,任何人都可以给出一个建议,在RelativeLayout
中动态添加一个与view
中的另一个view
相关的view
?
答
你在这里。这将完成你正在做的事情:
public class ExampleActivity extends Activity {
private RelativeLayout rl;
private EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
rl = (RelativeLayout) findViewById(R.id.main_rl);
editText = (EditText) findViewById(R.id.pref_edit_text);
Button button = new Button(this);
button.setText("Save");
// create the layout params that will be used to define how your
// button will be displayed
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// add the rule that places your button below your EditText object
params.addRule(RelativeLayout.BELOW, editText.getId());
// set the layoutParams on the button
button.setLayoutParams(params);
// add button to your RelativeLayout
rl.addView(button);
}
}
答
使用
Button b=new Button(this);
你必须创建新的按钮...并简单地增加使用布局 的ID main.xml中的布局像
LinearLayout layout=(LinearLayout) findViewById(R.id.linear);
layout.add(R.id.button);
您可以轻松地做这件事情动态添加按钮..
+0
谢谢,但你的建议只是在'LinearLayout'中添加一个按钮!我的主要问题是'如何在RelativeLayout中动态添加一个Button应该位于EditView(或任何视图)之下? '!无论如何,感谢您的回应! – 2012-07-14 13:07:33
谢谢,我会试试! – 2012-07-14 13:08:28
@KingfisherPhuoc你可以请指导我如何将多个动态按钮放置在相对布局中的随机位置 – 2017-02-02 12:08:28