`
fdyang
  • 浏览: 79710 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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);
	}
	

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics