滚动后,Edittext内容和复选框已更改

时间:2014-09-20 11:46:30

标签: java android listview checkbox

我有一个ListView,任何行都有一个Checkbox和Edittext。我制作了一个简单的适配器并用它来膨胀我的xml。但是在列表视图中滚动之后(如果列表大于一页),内容的Edittexts 复选框的复选标记 更改。我的适配器在下面。帮朋友们。

package com.moghaddasan.adinemarket;

import java.util.ArrayList;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;

public class BuyProductAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;

    ListView list;
    ArrayList<HashMap<String, String>> menuItems;
    BuyProductAdapter adapter;

    public BuyProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("InflateParams")
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        View vi=convertView;
        if(convertView==null){

            vi = inflater.inflate(R.layout.buy_row, null);
            holder = new ViewHolder();
            holder.mDetailEditText = (EditText)vi.findViewById(R.id.buy_prd_counter);
            holder.delChk = (CheckBox)vi.findViewById(R.id.delCheck); 
            vi.setTag(holder);
        }
        return vi;
    } 

    static class ViewHolder{
        public EditText mDetailEditText;
        public CheckBox delChk;
    }
}

1 个答案:

答案 0 :(得分:1)

由于您正在使用ListView,因此只要您开始滚动,您的行就会被回收(重复使用)。为了保持不同行的状态(选中复选框,EditText输入),您必须保存并在getView(...)方法中重新应用它们。

checkBox的基本思路

int mCheckBoxState[];

public BuyProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    // ...
    mCheckBoxState = new int[d.size];
}

// ...

public View getView(int position, View convertView, ViewGroup parent) {
    //...

    if(mCheckBoxState[position] == 0)
       holder.delChk.setChecked(false);
    else
       holder.delChk.setChecked(true);

    holder.delChk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (compoundButton == holder.delChk) {
            if (b) {
                mCheckBoxState[position] = 1;
            } else {
                mCheckBoxState[position] = 0;
            }
        }
      }
    });

    return vi;
}