通过单击按钮为多个edittext生成动态ID

时间:2013-08-13 11:15:13

标签: android android-edittext

我有一行EditText。我的方案是当用户点击按钮时,将添加另一行。不知怎的,我已经实现了这一点,但EditText都有相同的id。那么如何分配动态创建的EditText的id。我的EditText位于布局XML文件中。是否可以使用XML或我必须以编程方式创建EditText。 提前谢谢。

    private void inflateEditRow(String name) {

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.row, null);
    final ImageButton deleteButton = (ImageButton) rowView
            .findViewById(R.id.buttonDelete);
    final EditText editText = (EditText) rowView
            .findViewById(R.id.req);

    if (name != null && !name.isEmpty()) {
        editText.setText(name);
    } else {
        mExclusiveEmptyView = rowView;
        deleteButton.setVisibility(View.VISIBLE);
    }

    // A TextWatcher to control the visibility of the "Add new" button and
    // handle the exclusive empty view.
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            if (s.toString().isEmpty()) {
                mAddButton.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);

                if (mExclusiveEmptyView != null
                        && mExclusiveEmptyView != rowView) {
                    mContainerView.removeView(mExclusiveEmptyView);
                }
                mExclusiveEmptyView = rowView;
            } else {

                if (mExclusiveEmptyView == rowView) {
                    mExclusiveEmptyView = null;
                }

                mAddButton.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);
            }
        }


    public void onAddNewClicked(View v) {
    // Inflate a new row and hide the button self.
    inflateEditRow(null);
    v.setVisibility(View.VISIBLE);
}

2 个答案:

答案 0 :(得分:5)

为了动态生成View Id,请使用表单API 17

generateViewId()

这将生成适合setId(int)使用的值。该值不会与构建时为a R.id.

生成的ID值冲突

喜欢这个

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText editText = new EditText(MainActivity.this);
                editText.setId(editText.generateViewId());
                editText.setHeight(50);
                editText.setWidth(50);
                ll.addView(editText);

            }

答案 1 :(得分:3)

您可以在资源文件夹中列出可能id的列表,例如ids.xml,并在其中放置id,如下所示;

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <item type="id" name="edittext1" />
        <item type="id" name="edittext2" />
        <item type="id" name="edittext3" />
</resources>

然后在您的 Java 代码中为您的EditText代码设置动态ID;

youreditText1.setId(R.id.edittext1);
youreditText2.setId(R.id.edittext2);
youreditText3.setId(R.id.edittext3);