我有一个ArrayAdapter for listView里面有复选框。当复选框的值更改时,我想获取选中复选框的项目列表。
onCreate
我的活动的内部功能
ArrayAdapter<DrawerDetail> adapter = new ArrayAdapter<DrawerDetail>(this, R.layout.settings_minidrawer_item, apps) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = getLayoutInflater().inflate(R.layout.settings_minidrawer_item, null);
}
ImageView appIcon = (ImageView)convertView.findViewById(R.id.item_app_icon);
appIcon.setImageDrawable(apps.get(position).icon);
appIcon.setTag(apps.get(position).name);
TextView appLabel = (TextView)convertView.findViewById(R.id.item_app_name);
appLabel.setText(apps.get(position).label);
appLabel.setText(Integer.toString(position));
CheckBox appCheck = (CheckBox)convertView.findViewById(R.id.item_app_check);
appCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
UpdatePreferences();
}
});
return convertView;
}
};
list.setAdapter(adapter);
updatePreferences
public void UpdatePreferences() {
SharedPreferences.Editor prefEditor = prefs.edit();
SparseBooleanArray checked = list.getCheckedItemPositions();
List<String> drawerListArray = new ArrayList<String>();
View v;
CheckBox c;
for(int i = 0; i < list.getAdapter().getCount(); i++) {
v = list.getAdapter().getView(i, null, list);
c = (CheckBox) v.findViewById(R.id.item_app_check);
TextView aka = (TextView) v.findViewById(R.id.item_app_name);
aka.setText("dd");
Log.e("checked: ", Boolean.toString(c.isChecked()));
}
}
如果检查SparsBooleanArray checked
值,则始终为null。list.getAdapter().getView()
似乎也没有用。
此行找不到任何视图(不返回错误,但无法获取/设置值):
c = (CheckBox) v.findViewById(R.id.item_app_check);
TextView aka = (TextView) v.findViewById(R.id.item_app_name);
我尝试了不同的方法,但无法使其正常工作。现在,我的猜测是我正在重写getView
适配器的方法,并且它们彼此冲突,但是我无法提出任何方法来解决如何覆盖getView的问题,因为它对两者都适用。
不要检索这些视图。在onCheckedChangeListener中传递已检查/未检查的信息-例如,字符串和信息(如果已检查/未检查)。然后,您可以收集数组中的已检查项目。
尝试做这样的事情:
public class TestClass {
private List<String> checkedStrings = new ArrayList<>();
...
void updateArray(boolean checked, String checkedText){
if(checked){
if(!checkedStrings.contains(checkedText)){
checkedStrings.add(checkedText);
}
} else {
checkedStrings.remove(checkedText);
}
}
}
并在您的ArrayAdapter中:
appCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
updateArray(isChecked, apps.get(position).label);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句