Android 在布局容器中动态添加控件

这里,通过一个小demo,就可以掌握在布局容器中动态添加控件,以动态添加Button控件为例,添加其他控件同样道理。

1、addView

添加控件到布局容器

2、removeView

在布局容器中删掉已有的控件

3、使用,来个小demo就明白了

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 生成一个LinearLayout,作为布局容器来动态添加3个Button
		final LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		setContentView(layout);

		// 生成3个Button
		final Button btn1 = new Button(this);
		btn1.setText("1");
		btn1.setText("Button1");
		final Button btn2 = new Button(this);
		btn2.setText("2");
		btn2.setText("Button2");
		final Button btn3 = new Button(this);
		btn3.setText("3");
		btn3.setText("Button3");

		// 动态把三个Button添加到
		layout.addView(btn1);
		layout.addView(btn2);
		layout.addView(btn3);

		// 点击按钮时,先把原来在布局容器layout上的删掉,再添加上局容器layout,这样本次添加的控件就会排序到最后,以理解动态添加控件的思路
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				layout.removeView(btn1);
				layout.addView(btn1);
			}
		});

		// 同btn1一样道理
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				layout.removeView(btn2);
				layout.addView(btn2);
			}
		});

		// 同btn1一样道理
		btn3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				layout.removeView(btn3);
				layout.addView(btn3);
			}
		});
		setContentView(layout);
	}

}

 4、上图

相关文章

AdvserView.java package com.earen.viewflipper; import an...
ImageView的scaleType的属性有好几种,分别是matrix(默认)...
文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...