我已經使用ListView與自定義適配器,所以我的ListView包括複選框,但問題是,當我向下滾動,選中CheckBoxes取消選中,我該如何使用此代碼?如何在ListView中滾動時保存CheckBox的狀態?
UPDATE
我的自定義適配器:
public class AppsArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private List<Integer> checkedItems;
private final String DefaultApps = "def_apps";
public AppsArrayAdapter(Context context, String[] values, List<Integer> checkedItems) {//XXX
super(context, R.layout.apps, values);
this.context = context;
this.checkedItems = checkedItems;//XXX
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SharedPreferences myPrefsApps =context.getSharedPreferences("myPrefsApps", Context.MODE_PRIVATE);
String prefNameDefaultApps = myPrefsApps.getString(DefaultApps, "");
String prefNameDefaultAppsVer = myPrefsApps.getString(DefaultAppsVer, "");
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.apps, parent, false);
TextView text_apps = (TextView)rowView.findViewById(R.id.text_apps);
CheckBox check = (CheckBox)rowView.findViewById(R.id.check_apps);
text_apps.setText(prefNameDefaultApps.split("\n")[position]);
check.setChecked(checkedItems.contains((Integer) position));
return rowView;
}
}
我的活動:
public class AppsActivity extends ListActivity {
private final String DefaultApps = "def_apps";
private List<Integer> checkedItems = new ArrayList<Integer>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppsArrayAdapter adapter = new AppsArrayAdapter(this, prefNameDefaultApps.split("\n"), checkedItems);
setListAdapter(adapter);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(checkedItems.contains((Integer) position)) checkedItems.remove((Integer) position);
else checkedItems.add((Integer) position);
}
看看我的答案http://stackoverflow.com/questions/9309250/checkbox-gets-unchecked-on-scroll-in-a-custom-listview/14724554#14724554 – 2013-02-06 08:37:40