Tuesday, September 20, 2011

Listview using checkbox resolved issue.

// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
        int[] to) {
    super(context, layout, c, from, to);
    this.c = c;
    this.context = context;

    for (int i = 0; i < this.getCount(); i++) {
        itemChecked.add(i, false); // initializes all items value with false
    }
}
public View getView(final int pos, View inView, ViewGroup parent) {
    if (inView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inView = inflater.inflate(R.layout.your_layout_file, null);
    }

    final CheckBox cBox = (CheckBox) inView.findViewById(R.id.bcheck); // your
    // CheckBox
    cBox.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            CheckBox cb = (CheckBox) v.findViewById(R.id.your_checkbox_id);

            if (cb.isChecked()) {
                itemChecked.set(pos, true);
                // do some operations here
            } else if (!cb.isChecked()) {
                itemChecked.set(pos, false);
                // do some operations here
            }
        }
    });
    cBox.setChecked(itemChecked.get(pos)); // this will Check or Uncheck the
    // CheckBox in ListView
    // according to their original
    // position and CheckBox never
    // loss his State when you
    // Scroll the List Items.
    return inView;
}}

No comments:

Post a Comment

content -->