简单添加
btn事件中动态添加控件
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ImageView pic = new ImageView(MainActivity.this);
pic.setImageResource(R.drawable.ic_launcher);
pic.setId(100);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT
);
llContent.addView(pic);
}
});
复杂布局添加:
case R.id.tvMaintainAddBrand://点击添加车型,并且设置点击事件
LinearLayout temp = (LinearLayout) v.inflate(getActivity(), R.layout.trader_maintain_carbrand_adapter, null);
//R.layout.trader_maintain_carbrand_adapter
TextView tvCarBrandAdapter = (TextView) temp.findViewById(R.id.tvCarBrandAdapter);
TextView tvCarTypeAdapter = (TextView) temp.findViewById(R.id.tvCarTypeAdapter);
ImageView ivDelCarBrand = (ImageView) temp.findViewById(R.id.ivDelCarBrand);
setCarBrandListener(tvCarBrandAdapter, tvCarTypeAdapter, ivDelCarBrand);//设置监听事件
llCarBrandContent.addView(temp);
break;
/**
* 汽车品牌下拉框点击事
* @param tvCarTypeAdapter
* @param tvCarBrandAdapter
*/
private void setCarBrandListener(TextView tvCarBrandAdapter, TextView tvCarTypeAdapter, final ImageView ivDelCarBrand) {
tvCarBrandAdapter.setTag(tvCarTypeAdapter);
tvCarTypeAdapter.setTag(tvCarBrandAdapter);
//由于汽车品牌和汽车系列是相互关联的
tvCarBrandAdapter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
flag = 2;
TextView tvType = (TextView) v.getTag();
tvType.setText("");
initSpinerPopWindow(carBrandList, (TextView) v, tvType);//自定义下拉框
}
});
tvCarTypeAdapter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
flag = 2;
TextView tvBrand = (TextView) v.getTag();
String brand = tvBrand.getText().toString();
for (int i = 0; i < carBrandList.size(); i++) {
if (brand.equals(carBrandList.get(i).getName())) {
CarBrandEntity temp = (CarBrandEntity) carBrandList.get(i);
initSpinerPopWindow(temp.getTags(), (TextView) v, null);//自定义下拉框
}
}
}
});
ivDelCarBrand.setOnClickListener(new OnClickListener() {//删除特定的某个
@Override
public void onClick(View v) {
LinearLayout vp = (LinearLayout) ivDelCarBrand.getParent();
if (vp != null) {
LinearLayout vpp = (LinearLayout) vp.getParent();
if (vpp != null) {
if(vpp.getChildCount()>1){
vpp.removeView(vp);
}
if(vpp.getChildCount()==1){//如果只剩下一个就不要删除
TextView brand = (TextView) vp.getChildAt(0);
TextView type = (TextView) vp.getChildAt(1);
brand.setText("");
type.setText("");
}
}
}
}
});
}
//遍历取出所有添加的控件
for (int i = 0; i < llCarBrandContent.getChildCount() - 1; i++) {
LinearLayout temp1 = (LinearLayout) llCarBrandContent.getChildAt(i);
TextView brand1 = (TextView) temp1.getChildAt(0);
TextView type1 = (TextView) temp1.getChildAt(1);
String nextStr1 = brand1.getText().toString() + type1.getText().toString();
if (nextStr.equals(nextStr1)) {
Toast.makeText(getActivity(), "已经有此项", 1000).show();
return;
}