Android开发中向ListView中动态添加多个EditText并保存相应的EditText中的值
程序员文章站
2022-05-30 23:41:42
...
private ListViewAdapter mTKTAdapter;
private List<ItemBean> mTKTData;//这个集合保存的即是相应的EditText中你填写的值
在相应的Activity中调用,如下代码:mTKTData = new ArrayList<ItemBean>();
for (int i=0;i<addNum;i++){
ItemBean itemBean=new ItemBean();
itemBean.setText("你好");
mTKTData.add(itemBean);
}
mTKTAdapter = new ListViewAdapter(this, mTKTData);
mTKTAdapter.notifyDataSetChanged();
lvTKTEditTextList.setAdapter(mTKTAdapter);
其中的ListViewAdapter是自定义适配器,ItemBean是自己定义的一个泛型类。如下:
public class ListViewAdapter extends BaseAdapter {
private List<ItemBean> mData;
private Context mContext;
public ListViewAdapter(Context mContext, List<ItemBean> mData) {
this.mContext = mContext;
this.mData = mData;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_edittext, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ItemBean itemObj = mData.get(position);
if (holder.editText.getTag() instanceof TextWatcher) {
holder.editText.removeTextChangedListener((TextWatcher) holder.editText.getTag());
}
holder.editText.setText(itemObj.getText());
TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s)) {
itemObj.setText("");
} else {
itemObj.setText(s.toString());
}
}
};
holder.editText.addTextChangedListener(watcher);
holder.editText.setTag(watcher);
return convertView;
}
private class ViewHolder {
private EditText editText;
public ViewHolder(View convertView) {
editText = (EditText) convertView.findViewById(R.id.item_edittext_edittext);
}
}
}
public class ItemBean {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
其中,相应的item_edittext.xml的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="@+id/item_edittext_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
android:singleLine="true"
android:hint="请输入答案"
android:layout_margin="10dp"
android:padding="5dp"
android:background="@drawable/bg_edittext_selector"/>
</LinearLayout>
运行界面如下:
下一篇: mysql开发中遇到的问题解决