Activity 中动态增加控件

静态: layout/*.xml 布局 UI  。通过(ControlType)findViewById(R.id.name)来实例化。

动态: 通过 Java code 增加, ControlType control = new ControlType control 来实例化。

 

动态增加控件的基本思路就是:实例化控件-> 布局.addView(控件) -> OnCreat中绑定布局控件 setContentView(布局)

 

例1:在LinearLayout中动态增加Button,EditText等控件,并且点击Button后,动态增加EditText等控件。

 

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final LinearLayout linearLayout=new LinearLayout(this);  
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		
		LinearLayout linearLayout1 = new LinearLayout(this);
		linearLayout1.setOrientation(LinearLayout.VERTICAL);
		
		Button button1= new Button(this);
		button1.setText("增加新项目");
		
		Button button2 = new Button(this);
		button2.setText("增加新组");
		
		linearLayout.addView(button1);
		linearLayout.addView(button2);
		
		//设定按钮单击监听器,动态增加控件.
		button2.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				Context context = v.getContext();
				LinearLayout linearLayout2 = new LinearLayout(context);
				linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
				
				EditText groupNameEditText = new EditText(context);
				//设置控件大小.
				groupNameEditText.setWidth(160);
				
				ImageButton imagebutton1 = new ImageButton(context);
				Button saveButton = new Button(context);
				Button exitButton = new Button(context);
				
				linearLayout2.addView(groupNameEditText);
				linearLayout2.addView(imagebutton1);
				linearLayout2.addView(saveButton);
				linearLayout2.addView(exitButton);
				linearLayout.addView(linearLayout2);
				
			}
		});
		
		setContentView(linearLayout);
	}
	

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值