android---動態管理控件

簡單添加
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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章