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 を使用します。

generateViewId()

での使用に適した値を生成します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 に答える