Android中利用LinearLayout动态添加控件

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://lwkl.blogbus.com/logs/70517156.html

在androidUI布局中,一般都是利用xml来布局控件,这是比较方便和直观的,但是有时却需要动态生成,下面就举2个简单例子来说明怎么动态添加控件:

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

 

·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  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.    }  

 

与上一例子区别就是,在Button的OnClickListener中动态添加控件,需要注意的一点是 Button btn3=new Button(v.getContext);参数v.getContext为当前view的context,为什么例子1中用this作为context呢,呵呵,这是因为this即当前的activity,而activity又是context的子类,所以this就可以直接作为activity了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值