【发布时间】:2014-02-18 07:23:27
【问题描述】:
我正在开发一个安卓应用程序。在这个列表视图中,每个项目都有复选框。
默认情况下所有项目都被选中。对于复选框,我已应用 onClickListener。每当用户单击复选框时,我都会在当前定位的 bean 类中设置值 true。
一切都很好。但是 Ui 正在更新两个替代项目而不是一个。 例如,如果我点击第二个复选框,那么第四个复选框也在用户界面中更新。点击监听器只调用一次。
下面是适配器类中点击监听的代码。
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listview = convertView;
listview = inflater.inflate(R.layout.edit_group_users_item, null);
//Get all the fields of the layout
userTV = (TextView) listview.findViewById(R.id.code);
checkbox = (CheckBox) listview.findViewById(R.id.checkBox1);
userTV.setText(userList.get(position).getUserName());
checkbox.setChecked(true);
checkbox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("Position is:", ""+position);
Log.v("Befoer checkbox status is:", ""+GroupsAdapter.group_users.get(position).isSelected());
if(!GroupsAdapter.group_users.get(position).isSelected()) {
//set the value to true in the user bean
GroupsAdapter.group_users.get(position).setSelected(true);
checkbox.setChecked(true);
} else {
//set the value to false in the user bean
GroupsAdapter.group_users.get(position).setSelected(false);
checkbox.setChecked(false);
}
}
});
return listview;
}
我不知道出了什么问题。请告诉我如何解决上述问题。
【问题讨论】:
-
checkbox.setChecked(true);在 clickListener 将每一行设置为选中之前!!!
-
建议:维护一个列表,在其中只存储那些被检查的项目。并在 getView 方法中检查该项目是否存在于列表中,如果是,则检查它,否则不检查。在 onclick 监听器中,调用 Activity 中仅调用 notifyDatasetChanged 的方法。
标签: android checkbox android-listview onclicklistener