【发布时间】:2017-09-15 12:54:32
【问题描述】:
我用 Textview 和 Checkbox 创建了一个 Listview。首先,我将所有项目保持为选中默认值。
但是当我取消选中复选框并向下滚动以取消选中列表视图中的其他一些项目时,会选中较旧的项目。请帮我写代码。
这是我的适配器类代码。
@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
try {
ViewHolder holder = new ViewHolder();
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = layout_inflater.inflate(R.layout.dashbordmenu_listadapter, null);
holder.txtMenutitle = (TextView) convertView.findViewById(R.id.txtPersonList);
holder.checkAppList = (CheckBox) convertView.findViewById(R.id.checkPersonList);
convertView.setTag(holder);
convertView.setTag(R.id.txtPersonList, holder.txtMenutitle);
convertView.setTag(R.id.checkPersonList, holder.checkAppList);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkAppList.setTag(position);
holder.txtMenutitle.setText(arrayListDashboard1.get(position).getMenuTitle());
holder.checkAppList.setChecked(arrayListDashboard1.get(position).isSelected());
holder.checkAppList.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int selectPosition = (int) buttonView.getTag();
if(buttonView.isChecked())
{
selectedAppId = arrayListDashboard1.get(selectPosition).getMenuId();
Log.d("TEST","selectedAppId = "+selectedAppId);
} else {
notSelectedAppId = arrayListDashboard1.get(selectPosition).getMenuId();
Log.d("TEST","notSelectedAppId = "+notSelectedAppId);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
TextView txtMenutitle;
public CheckBox checkAppList;
}
【问题讨论】:
-
holder.checkAppList.setChecked(arrayListDashboard1.get(position).isSelected());这行可能是问题所在。也许尝试将每个视图的状态保存在ArrayList<Boolean>或Map<View, Boolean> -
此外,
isSelected()不等于isChecked()