如何使用 LayoutInflater 动态添加 editText 和按钮并为它们设置唯一的 id?

How to add editText and buttons dynamically using LayoutInflater and set a unique id for them?

我正在为产品添加规格,我希望当用户单击 add_field_btn 时,它会显示 XML 文件包含两个 editText,侧面有一个删除按钮,使用布局充气器。但是我不知道如何为生成的每个 editText 添加一个唯一的 id。

下面是我的代码:

MainActivity

@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;
            }

        }