我有一個行的 EditText
。我的情況是當(dāng)用戶點擊一個按鈕,另一個將添加行。我不知怎么實現(xiàn)這個,但兩個 EditText
有相同的 id。所以如何分配的 id EditText
動態(tài)創(chuàng)建。我 EditText
是在布局的 XML 文件。是可能的與 XML 或我要創(chuàng)建 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);
}
解決方法 1:
以便動態(tài)生成使用窗體視圖 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);
}