Để giải quyết vấn đề này, bạn sẽ phải tạo một Hạng mục tùy chỉnh sẽ đại diện cho các hộp kiểm riêng lẻ của bạn trong danh sách. Sau đó, mảng các mục này sẽ được lớp bộ điều hợp sử dụng để hiển thị các hộp kiểm của bạn.
Hạng mục này sẽ có biến boolean được chọn sẽ xác định xem hộp kiểm có được chọn hay không. Bạn sẽ phải thiết lập giá trị của biến này trong Phương pháp OnClick bạn của lớp bộ chuyển đổi tùy chỉnh của bạn
Ví dụ
class CheckBoxItem{
boolean isSelected;
public void setSelected(boolean val) {
this.isSelected = val;
}
boolean isSelected(){
return isSelected;
}
}
Đối CustomAdapter Lớp của bạn mà trông giống như sau:
public class ItemsAdapter extends ArrayAdapter implements OnClickListener {
// you will have to initialize below in the constructor
CheckBoxItem items[];
// You will have to create your check boxes here and set the position of your check box
/// with help of setTag method of View as defined in below method, you will use this later // in your onClick method
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
CheckBox cBox = null;
if (v == null) {
LayoutInflater vi = (LayoutInflater) apUI.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.attachphoto, null);
}
CheckBoxItemItem it = items[position];
cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
cBox.setOnClickListener(this);
cBox.setTag(""+position);
Log.d(TAG, " CHECK BOX IS: "+cBox+ " Check Box selected Value: "+cBox.isChecked()+" Selection: "+it.isSelected());
if(cBox != null){
cBox.setText("");
cBox.setChecked(it.isSelected());
}
return v;
}
public void onClick(View v) {
CheckBox cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
int position = Integer.parseInt((String) v.getTag());
Log.d(TAG, "CLicked ..."+cBox.isChecked());
items[position].setSelected(cBox.isChecked());
}
}
Sau đó bạn sẽ khai báo và mảng của lớp CheckBoxItem của bạn sẽ được chứa trong lớp Adapter của bạn trong trường hợp này nó sẽ là lớp ItemsAdapter.
Sau đó, khi người dùng nhấn nút bạn có thể lặp qua tất cả các mục trong mảng và kiểm tra xem mục nào được chọn bằng cách sử dụng phương thức isSelected() của lớp CheckBoxItem.
Trong hoạt động của bạn, bạn sẽ có:
ArrayList getSelectedItems(){
ArrayList selectedItems = new ArrayList();
int size = items.length;
for(int i = 0; i<size; i++){
CheckBoxItem cItem = items[i];
if(cItem.isSelected()){
selectedItems.add(cItem);
}
}
return selectedItems;
}
Nguồn
2012-06-06 10:10:08
http://stackoverflow.com/questions/10895763/checkbox-unchecked-when-i-scroll-listview-in-android/10896140#comment14205583_10896140 –