我想先显示一个带有空白edittext的列表视图,然后在按钮点击时添加新的空白edittexts。现在添加了edittext,但是当我添加新的edittext时,我添加到这些空白edittexts的任何数据都会被删除。此外,当我删除一个项目时,所有数据都会从剩余的edittexts中删除。
// row layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<EditText
android:id="@+id/myEt"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/delImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="@android:drawable/ic_delete"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Button openBtn;
ArrayList<Model> listItems=new ArrayList<Model>();
ContactsListAdapter adapter;
int resource;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openBtn = (Button) findViewById(R.id.openBtn);
list = (ListView)findViewById(R.id.list);
adapter = new ContactsListAdapter(this, resource, listItems);
list.setAdapter(adapter);
openBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addItems();
}
});
}
public void addItems() {
Model model = new Model();
model.setCount(listItems.size()+1);
listItems.add(model);
adapter.notifyDataSetChanged();
}
}
public class ContactsListAdapter extends ArrayAdapter<Model> {
private Context mContext;
int resource;
private ArrayList<Model> arrayList = new ArrayList<Model>();
public ContactsListAdapter(Context mContext, int resource, ArrayList<Model> arrayList) {
super(mContext, resource, arrayList);
this.resource = resource;
this.mContext = mContext;
this.arrayList = arrayList;
}
@Override
public int getCount() {
return super.getCount();
}
@NonNull
@Override
public View getView(final int position, View convertView, @NonNull final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
v = inflater.inflate(R.layout.contact_item, parent, false);
holder.myEt = (EditText)v.findViewById(R.id.myEt);
holder.delImg = (ImageView)v.findViewById(R.id.delImg);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Model item = arrayList.get(position);
holder.myEt.setText(item.getName());
holder.delImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
arrayList.remove(position);
notifyDataSetChanged();
}
});
return v;
}
class ViewHolder {
EditText myEt;
ImageView delImg;
}
}