-2

Checkbox auto call onCheckedChange when listview scroll?

got solution in this link but I still have trouble..I have tab host in my app so once i switch it to it and when i come back to the list the problem still prevails automatically my 1st as well as the last items get checked... Help me.. Thanks in advance

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;
    }
}
Community
  • 1
  • 1
Sathish
  • 11
  • 2

1 Answers1

0

You can achieve this by using simple codes , Listview already has property ChoiceMode. You can set it to CHOICE_MODE_MULTIPLE.

Here is the code sample from android sample projects-

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

Sanjeet A
  • 5,171
  • 3
  • 23
  • 40