Android 使自定义ListView中的复选框正常工作
我的listview有一个自定义的行布局:Android 使自定义ListView中的复选框正常工作,android,listview,checkbox,adapter,Android,Listview,Checkbox,Adapter,我的listview有一个自定义的行布局: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <CheckBox android:id="@+id/chkbox" andr
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
抱歉,如果这是一种完全错误的方法,但这不应该工作吗?结果是整个列表和选中状态都不正确,我做错了什么?一些离题评论: 首先,你不需要这个:
Map<String, String> selectedgroup = new HashMap<String, String>();
然后,您可以使用一个列表来代替列表
关于onCheckedChangeListener
,您可以使用复选框中的文本迭代列表,以找到正确的位置,然后更改值。如果文本不是唯一的,
您可以在ListView上使用一个保持单击位置的OnItemClickListener
,而不是使用onCheckedChangeListener
。好的,我想我知道了,我使用selectedgroup映射中的一个静态id值作为itm映射中的键来查找复选框的选中/未选中状态。使用视图是错误的方法,因为它们不能用作键。感谢您提供的离题内容!目前我没有保存选择状态,似乎这就是问题所在?那么,我如何保存状态以及如何将这些信息返回给活动?谢谢。
public class AdapterCustomBoxes extends ArrayAdapter<Map<String, String>> {
private List<Map<String, String>> list;
private List<Map<String, String>> orig_list;
private Context upper_context;
private View view;
public AdapterCustomBoxes(Context context, int textViewResourceId, ArrayList<Map<String, String>> items) {
super(context, textViewResourceId, items);
this.list = items;
this.orig_list = items;
this.upper_context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)upper_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_check_row, null);
}
Map<String, String> selectedgroup = new HashMap<String, String>();
selectedgroup = (Map<String, String>) list.get(position);
String itemtext = (String) selectedgroup.get("item_text");
TextView row_text = (TextView) view.findViewById(R.id.text);
row_text.setText(itemtext);
return view;
}
}
private Map<View, Boolean> itm = new HashMap<View, Boolean>();
CheckBox chkbox = (CheckBox) view.findViewById(R.id.chkbox);
chkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
itm.put(buttonView, isChecked);
}
});
if(itm.containsKey(chkbox)){
iteminfo_row_chkbox.setChecked( itm.get(chkbox) );
}else{
iteminfo_row_chkbox.setChecked(false);
}
Map<String, String> selectedgroup = new HashMap<String, String>();
Map<String, String> selectedgroup = (Map<String, String>) list.get(position);
private class ListItem{
String text;
boolean value;
}