动态生成linearLayout

时间:2021-04-12 08:38:27

LinearLayout linearLayout=new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams param=
new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(param);
// 每个layout都是一个ViewGroup
// linearLayout.addView(child);
// linearLayout.removeView(view);

TextView textview=new TextView(this);
textview.setText("hello world");
textview.setTextSize(30);

textview.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

ViewGroup group = (ViewGroup) v.getParent();
TextView textview = new TextView(MainActivity.this);
textview.setText("this is onclickListener");
textview.setTextSize(30);
textview.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ViewGroup group = (ViewGroup) v.getParent();
group.removeView(v);
}
});

group.addView(textview);

}
});

linearLayout.addView(textview);
this.setContentView(linearLayout);//将linearlayout添加到视图中
}