在activity中或fragment中动态添加布局
效果
项目结构
核心代码:
MainActivity
public class MainActivity extends Activity implements OnClickListener {
private Button btn_jiazaibuju;//加载按钮
private LinearLayout yuanbuju;//母布局
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btn_jiazaibuju.setOnClickListener(this);
}
/**
* 加载布局的按钮点击事件
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_jiazaibuju:
setView();
break;
}
}
/**
* 加载布局的方法
*/
private ArrayListviews = new ArrayList();//放view的list
private void setView() {
//移除其中的所有view
yuanbuju.removeAllViews();
//给要加载的布局设置参数
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
params.leftMargin = 30;
params.rightMargin = 30;
params.topMargin = 30;
//调inflate方法把布局转化成对象
View view1 = View.inflate(this, R.layout.jiedan_item, null);
View view2 = View.inflate(this, R.layout.jiedan_item, null);
View view3 = View.inflate(this, R.layout.jiedan_item, null);
View view4 = View.inflate(this, R.layout.jiedan_item, null);
View view5 = View.inflate(this, R.layout.jiedan_item, null);
//把布局对象放到list中
views.add(view1);
views.add(view2);
views.add(view3);
views.add(view4);
views.add(view5);
//在增强for循环中加载所有布局
for (View view:views) {
yuanbuju.addView(view, 0, params);
}
}
/**
* 初始化原控件
*/
private void init() {
yuanbuju = (LinearLayout) findViewById(R.id.layout_taskfragment_container);
btn_jiazaibuju = (Button) findViewById(R.id.btn_jiazaibuju);
}
}
activity_main.xml
jiedan_item.xml
如果没有明白下载我的例子
例子1动态加载
http://download.csdn.net/detail/zhaihaohao1/8352921
例子2动态加载,并分组
效果图:
http://download.csdn.net/detail/zhaihaohao1/8866307