【发布时间】:2017-06-13 13:22:36
【问题描述】:
大家好,我正在尝试在xml 文件中声明的CheckBox 上设置一个OnCheckedChangeListener,它代表ListView (item_todo.xml) 的单行,在这里复选框的代码:
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:text="" />
这里是listview的部分代码(fragment_bacheca.xml):
<ListView
android:id="@+id/listView1"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
然后我使用自定义适配器:`
public class TaskListAdapter extends ArrayAdapter<TaskCell>{
public TaskListAdapter(Context context, int textViewResourceId, List<TaskCell> objects){
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_todo, null);
TextView task_subject = (TextView) convertView.findViewById(R.id.task_subject);
TextView task_type = (TextView) convertView.findViewById(R.id.task_type);
TextView task_data = (TextView) convertView.findViewById(R.id.task_data);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
TaskCell t = getItem(position);
task_subject.setText(t.getMateria());
task_type.setText(t.getTipo());
task_data.setText(t.getData());
if(t.getFatto().equals("1")) {
cb.setChecked(true);
task_subject.setPaintFlags(task_subject.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
cb.setChecked(false);
}
return convertView;
}
TaskCell是todo_item的数据类。
这里是我调用监听器的片段代码:
taskView = getActivity().getLayoutInflater().inflate(R.layout.item_todo, null);
checkbox_task = (CheckBox) taskView.findViewById(R.id.checkBox1);
checkbox_task.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
adapter.notifyDataSetChanged();
}
});
list = new LinkedList<>();
adapter = new TaskListAdapter(getContext(), R.layout.item_todo, list);
lv.setAdapter(adapter);
问题是什么都没有发生,在调试中我看到onCheckedChanged 永远无法到达。
有人知道为什么吗?谢谢大家
【问题讨论】:
-
这可能不是原因,但您在问题描述中提到了
todo_item.xml作为文件名,但我在代码中看到了item_todo。我在代码中看不到todo_item.xml。 -
我解释错了,我打算item_todo.xml
-
OnCheckedChangeListener()应该在适配器而不是片段内部实现。 -
如果我在适配器上实现它,进程会执行 onCheckedChanged(我通过调试看到它)但复选框仍然未选中并且没有任何反应......
标签: android listview checkbox oncheckedchanged