2

I have one row with EditText. My scenario is when user clicks on a button another row will be added. Somehow I have achieved this but both EditText have same id. So how to assign the id of EditText dynamically created. My EditText is in the layout XML file. Is it possible with XML or I have to create EditText programatically. Thanks in advance.

    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);
}
4

2 回答 2

5

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

生成ViewId()

这将生成一个适合在setId(int). 此值不会与 aapt 在构建时生成的 ID 值冲突R.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);

            }
于 2013-08-13T11:35:27.610 回答
3

您可以id在资源文件夹中列出可能的 s,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代码中为你的s设置动态ID,EditText如下所示;

youreditText1.setId(R.id.edittext1);
youreditText2.setId(R.id.edittext2);
youreditText3.setId(R.id.edittext3);
于 2013-08-13T11:22:15.657 回答