Android中利用LinearLayout动态添加控件

1.动态添加2个垂直排列的Button

 1 @Override
 2     public void onCreate(Bundle savedInstanceState) {
 3         super.onCreate(savedInstanceState);
 4        //setContentView(R.layout.main);     
 5        final LinearLayout layout2=new LinearLayout(this);
 6         layout2.setOrientation(LinearLayout.VERTICAL);
 7         Button btn1=new Button(this);
 8         setContentView(layout2);
 9         Button btn2=new Button(this);
10         btn1.setText("Button1");
11         btn2.setText("Button2");
12         layout2.addView(btn1);
13         layout2.addView(btn2);
14 
15 
16        setContentView(layout2);
17 }

final LinearLayout layout2=new LinearLayou(this);

定义一个LinearLayout ,参数为context在这儿即为this

layout2.setOrientation(LinearLayout.VERTICAL);

设置layout格式为vertical,竖直排列

2.在Button的click事件中动态添加一个button

 1 OnClickListener listen1;
 2     @Override
 3     public void onCreate(Bundle savedInstanceState) {
 4         super.onCreate(savedInstanceState);
 5        //setContentView(R.layout.main);     
 6        final LinearLayout layout2=new LinearLayout(this);
 7         layout2.setOrientation(LinearLayout.VERTICAL);
 8         Button btn1=new Button(this);
 9         setContentView(layout2);
10         Button btn2=new Button(this);
11         btn1.setText("Button1");
12         btn2.setText("Button2");
13         layout2.addView(btn1);
14         layout2.addView(btn2);       
15         listen1 = new OnClickListener() {
16             public void onClick(View v) {
17                 setTitle("点击button1 ");
18                 Button btn3=new Button(v.getContext());
19                 layout2.addView(btn3);
20                 btn3.setText("Button3");
21 
22 
23             }
24         };
25          btn1.setOnClickListener(listen1);
26     }

 

转载于:https://www.cnblogs.com/yimi-yangguang/p/5715318.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值