我想为listview中每个项目中的每个开关设置一个单独的监听器。我该如何完成这项工作?
我的异步任务中调用的方法是setQueues:
private void setQueues(final JSONObject[] qInfo)
{
queues = new QueueItem[qInfo.length]; // QueueItem consists of a string(label) and a boolean(value)
for(int i = 0; i < qInfo.length; i++)
{
queues[i] = new QueueItem();
//final int ii = i;
// Formatting the queue title
String name = qInfo[i].optString("name").replace("-", " ");
name = name.replace("_", " ");
name = name.replace("ipinion", "");
name = name.replace(" ", " ");
name = capitalizeFirstLetters(name);
queues[i].label = name;
try {
if(qInfo[i].getString("active").contains("1"))
{
Log.d("QBox", "Queue: Checkbox " + i + " : Checked TRUE");
queues[i].value = true;
}
else
{
Log.d("QBox", "Queue Checkbox " + i + " : Checked FALSE");
queues[i].value = false;
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
lv.setAdapter(new QueueAdapter(getActivity(),
R.layout.queues_items, queues));
}
非常感谢任何帮助。我觉得我错过了一些非常明显的东西。
编辑:来自QueueAdapter的getView方法:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
QueueHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new QueueHolder();
holder.queueswitch = (Switch)row.findViewById(R.id.queues_item_switch);
holder.txtLabel = (TextView)row.findViewById(R.id.queues_item_text);
row.setTag(holder);
}
else
{
holder = (QueueHolder)row.getTag();
}
QueueItem queue = data[position];
holder.txtLabel.setText(queue.label);
holder.queueswitch.setChecked(queue.value);
// Is this where you would set up your listener?
return row;
}
答案 0 :(得分:0)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
QueueHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new QueueHolder();
holder.queueswitch = (Switch)row.findViewById(R.id.queues_item_switch);
/* TRY PUTTING IT HERE */
holder.txtLabel = (TextView)row.findViewById(R.id.queues_item_text);
row.setTag(holder);
}
else
{
holder = (QueueHolder)row.getTag();
}
QueueItem queue = data[position];
holder.txtLabel.setText(queue.label);
holder.queueswitch.setChecked(queue.value);
holder.queueswitch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//DO SOMETHING
}
});
return row;
}
这样就行了!我不确定,但尝试把它放在“/ *尝试把它放在这里* /”的地方,我不确定它是否会起作用但是它会更好,因为onClickListener的启动只发生一次......