滚动列表时,复选框会更改其值

时间:2015-07-26 06:24:13

标签: android listactivity listadapter

Checkbox auto call onCheckedChange when listview scroll?

在这个链接中得到了解决方案,但我仍然遇到麻烦..我的应用程序中有标签主机,所以一旦我将其切换到它,当我回到列表时,问题仍然自动优先于我的第一项以及最后一项得到检查...帮助我..提前致谢

public class FoodAdapter extends ArrayAdapter {
    private List<Food> list= new ArrayList<Food>()  ;
    private Context context;
    public FoodAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    static class ListHolder
    {
        TextView FOOD_NAME;
        CheckBox CHECK;

    }

    public void addToList(List<Food> list)
    {
        this.list = list;
    }

    public  int getCount()
    {
        return this.list.size();

    }

    public  Object getItem(int position)
    {
        return this.list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View list = convertView;
        final ListHolder listHolder;
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            list = inflater.inflate(R.layout.custom_list, parent, false);
            listHolder = new ListHolder();
            listHolder.FOOD_NAME = (TextView) list.findViewById(R.id.textView);
            listHolder.CHECK = (CheckBox) list.findViewById(R.id.checkBox);
            list.setTag(listHolder);

        }
        else {
            listHolder = (ListHolder) list.getTag();
        }
        final Food food = (Food) getItem(position);
        listHolder.FOOD_NAME.setText(food.getFood_name());
        listHolder.CHECK.setOnCheckedChangeListener(null);
        listHolder.CHECK.setChecked(food.isSeleted());
        listHolder.CHECK.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    listHolder.CHECK.setChecked(true);
                    food.setSeleted(true);

                } else {
                    listHolder.CHECK.setChecked(false);
                    food.setSeleted(true);
                }
            }
        });


        return list;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过使用简单代码实现此目的,Listview已经具有属性ChoiceMode。您可以将其设置为CHOICE_MODE_MULTIPLE。

以下是来自android示例项目的代码示例 -

https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List11.java?autodive=0%2F%2F