
例1:在LinearLayout中动态增加Button,EditText等控件,并且点击Button后,动态增加EditText等控件。
Java代码
1.@Override
2.protected void onCreate(Bundle savedInstanceState) {
3.super.onCreate(savedInstanceState)
4.final LinearLayout linearLayout=new LinearLayout(this)
5.linearLayout.setOrientation(LinearLayout.VERTICAL)
6.
7.LinearLayout linearLayout1 = new LinearLayout(this)
8.linearLayout1.setOrientation(LinearLayout.VERTICAL)
9.
10.Button button1= new Button(this)
11.button1.setText("增加新项目")
12.
13.Button button2 = new Button(this)
14.button2.setText("增加新组")
15.
16.linearLayout.addView(button1)
17.linearLayout.addView(button2)
18.
19.//设定按钮单击监听器,动态增加控件.
20.button2.setOnClickListener(new Button.OnClickListener(){
21.public void onClick(View v) {
22.Context context = v.getContext()
23.LinearLayout linearLayout2 = new LinearLayout(context)
24.linearLayout2.setOrientation(LinearLayout.HORIZONTAL)
25.
26.EditText groupNameEditText = new EditText(context)
27.//设置控件大小.
28.groupNameEditText.setWidth(160)
29.
30.ImageButton imagebutton1 = new ImageButton(context)
31.Button saveButton = new Button(context)
32.Button exitButton = new Button(context)
33.
34.linearLayout2.addView(groupNameEditText)
35.linearLayout2.addView(imagebutton1)
36.linearLayout2.addView(saveButton)
37.linearLayout2.addView(exitButton)
38.linearLayout.addView(linearLayout2)
39.
40.}
41.})
42.
43.setContentView(linearLayout)
44.}
45.
在Fragment中添加一个布局容器,并设置ID,在Activity中findbyview找到后,就可以动态添加了。
代码如下:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/first_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/first_button"/>
<Button
android:id="@+id/second_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/second_button"/>
<Button
android:id="@+id/third_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/third_button"/>
</LinearLayout>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)