我正在为product添加规格,我希望当用户单击add_field_btn
时,它将使用LayoutInflater在XML文件中包含两个editText,并在侧面显示一个删除按钮。但是我不知道如何为生成的每个editText添加唯一的ID。
下面是我的代码:
主要活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_products);
backBTN = findViewById(R.id.imageButton);
backBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(AddProductsActivity.this, StoreHomeActivity.class);
intent.putExtra("userid", userID);
startActivity(intent);
overridePendingTransition(R.anim.mid_to_left, R.anim.right_to_mid);
}
});
}
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.product_specification_item_layout, null);
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
分析解答
您走对了路;只需检查下面我修改的功能。
int myTagCount=0;
public void onAddField(View v) {
myTagCount++;
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.product_specification_item_layout, null);
TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
tv_delete.setText("Delete");
tv_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
parentLinearLayout.removeView(view);
}
});
view.setTag(myTagCount);
parentLinearLayout.addView(view);
}
我以这种方式使用inflater
。这也将为您提供帮助。
对于getting value with Tag
,请检查以下内容:
for (int i = 0; i < parentLinearLayout.getChildCount(); i++) {
View view = parentLinearLayout.getChildAt(i);
if (view.getTag().equals(myTagCount)) {
EditText editText = (EditText) view.findViewById(R.id.edt1);
String myText = editText.getText().toString();
break;
}
}