ListView里有Button和EditText是记录EditText状态
项目里要做点菜的功能,大概是两个Button中间一个EditText,点击可以改变EditText内容,问题是,当页面跳转之后再返回时,记不住EditText的状态,参考了
http://blog.sina.com.cn/s/blog_65570a20010108lp.html 自己实现了记住点了几份菜的信息。代码如下,用一个HashMap去记录状态,Adapter如下
/** * @author ypeng * */ public class DishAdapter extends BaseAdapter { private Activity context; private List<BooK> dishlist; // 用来记录所有ListView记录对应EditText的状态 public HashMap<Integer, String> isChanged; public DishAdapter(Activity context, List<BooK> dishlist) { this.context = context; this.dishlist = dishlist; init(); } public HashMap<Integer, String> getIsChanged() { return isChanged; } private void init() { isChanged = new HashMap<Integer, String>(); for (int i = 0; i < dishlist.size(); i++) { isChanged.put(i, "0"); } } @Override public int getCount() { // TODO Auto-generated method stub return dishlist.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return dishlist.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = LayoutInflater.from(context).inflate(R.layout.menu_item, null); TextView resName;// 菜品名称 TextView resPrice;// 菜品单价 TextView resDiscount;// 折扣 Button addnum;// 加一份 Button minusnum;// 减一份 final EditText resNum;// 点几份 resName = (TextView) convertView.findViewById(R.id.menu_item_dishname); resPrice = (TextView) convertView .findViewById(R.id.menu_item_dishprice); resDiscount = (TextView) convertView .findViewById(R.id.menu_item_dishdiscount); resNum = (EditText) convertView.findViewById(R.id.dishnum); addnum = (Button) convertView.findViewById(R.id.OneDish); minusnum = (Button) convertView.findViewById(R.id.MoreDish); String name = dishlist.get(position).getName(); double price = dishlist.get(position).getPrice(); double discount = dishlist.get(position).getDiscount(); resName.setText(name); resPrice.setText(Double.toString(price)); resDiscount.setText(Double.toString(discount)); addnum.setOnClickListener(new OnClickListener() { public void onClick(View v) { int num = Integer.valueOf(resNum.getText().toString()); num++; resNum.setText(Integer.toString(num)); dishlist.get(position).setNum(num); isChanged.put(position, Integer.toString(num)); } }); minusnum.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int num = Integer.valueOf(resNum.getText().toString()); if (num > 0) { num--; resNum.setText(Integer.toString(num)); dishlist.get(position).setNum(num); isChanged.put(position, Integer.toString(num)); } if (num == 0) {// 必须判断,不判断出错 resNum.setText(Integer.toString(0)); dishlist.get(position).setNum(num); isChanged.put(position, Integer.toString(num)); } } }); resNum.setText(isChanged.get(position)); return convertView; } }