如何在適配器來看,Android的,ArrayAdapter,onCheckedChanged添加一個偵聽複選框,OnCheckedChangeListener
我有一個ListView通過一個ArrayAdapter的方式是由小的XML子視圖填充。每個小視圖裏面只有兩件東西,一個複選框和一個字符串標籤。
我想設置一個onCheckedChanged偵聽器來捕獲用戶檢查或取消選中複選框的事件。
例如此處顯示的聽衆:
listView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Toast.makeText(this, "box has been checked", Toast.LENGTH_SHORT).show();
}
}
我在哪裏把監聽器代碼?我該如何設置它?對於一個ArrayAdapter
代碼:
public class MobileArrayAdapter extends ArrayAdapter<CheckBoxInfo>{
CheckBoxInfo[] objects;
Context context;
int textViewResourceId;
public MobileArrayAdapter(Context context, int textViewResourceId,
CheckBoxInfo[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.textViewResourceId = textViewResourceId;
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row_layout_view = convertView;
if ((row_layout_view == null)){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row_layout_view = inflater.inflate(R.layout.row_layout, null);
}
//CheckBoxInfo item = objects.get(position); // for arrayList
CheckBoxInfo item = objects[position];
if(item != null){
TextView textView = (TextView) row_layout_view.findViewById(R.id.textView1);
CheckBox checkBox = (CheckBox) row_layout_view.findViewById(R.id.checkBox1);
if(item !=null){
textView.setText(item.checkBoxName);
checkBox.setChecked(item.checkBoxState);
}
}
return row_layout_view;
}
}
我不認爲這個工程,因爲列表視圖回收的觀點。當您向下滾動並選定的convertView被回收時,選中的行將變爲未選中狀態。你如何解決這個問題? – 2014-08-25 08:10:27
這是正確的行爲。當視圖被重用時,其所有的子視圖中的孩子都具有被回收的無意義視圖的特徵。因此,您必須每次更新'getView()'中的所有視圖及其屬性。這包括設置CheckBox值以及其OnClickListener。總之,如果回收(或新)視圖具有不同的設置,請保持偵聽器並添加'checkBox.setChecked()'將其設置爲預期值。 – 2014-08-26 01:16:36