问题:获取在ListView的item中EditText输入值
解决办法:在adapter中使用TextWatcher来保存EditText中输入的值
代码:
public class SimpleAdapter extends BaseAdapter {
private Context context;
private List dataList;
private LayoutInflater inflater;
public SimpleAdapter(Context context, List<UserBean> dataList) {
super();
this.context = context;
this.dataList = dataList;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder(convertView, position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
UserBean bean = dataList.get(position);
holder.name.setText(bean.getName());
holder.age.setText(bean.getAge());
return convertView;
}
private class ViewHolder {
private TextView name;
private EditText age;
public ViewHolder(View view,int position) {
name = (TextView) view.findViewById(R.id.name);
age = (EditText) view.findViewById(R.id.age);
age.setTag(position);
age.addTextChangedListener(new TextSwitcher(this));
}
}
class TextSwitcher implements TextWatcher {
private ViewHolder mHolder;
public TextSwitcher(ViewHolder mHolder) {
this.mHolder = mHolder;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int position = (int) mHolder.age.getTag();
((MainActivity)context).saveEditData(position, s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
}
}
public class MainActivity extends Activity {
private ListView listView;
private List dataList;
private SimpleAdapter adapter;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataList = new ArrayList<UserBean>();
btn = (Button) findViewById(R.id.btn);
listView = (ListView) findViewById(R.id.listView);
adapter = new SimpleAdapter(this, dataList);
listView.setAdapter(adapter);
initdData();
btn.setOnClickListener(mOnClickListener);
}
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
String str = new Gson().toJson(dataList);
Log.d("TEST", "str:"+str);
break;
default:
break;
}
}
};
public void saveEditData(int position, String str) {
dataList.get(position).setAge(str);
}
private void initdData() {
UserBean bean = new UserBean();
bean.setId("1001");
bean.setName("张三");
dataList.add(bean);
bean = new UserBean();
bean.setId("1002");
bean.setName("李四");
dataList.add(bean);
adapter.notifyDataSetChanged();
}
}