Reputation: 153
I have looked other questions but none of them fulfill what I need.
I have a listview showing a list of objects (alarms) that have some textviews and a checkbox. As you can imagine, this checkbox is to activate and deactivate that alarm.
When I arrive to this screen (alarms list), it checks the active state in the database, so some of the checkboxes are checked and some other not.
What I need is to click in the checkbox and change the state in the database for that alarm at the moment. Not checking the state of all checkboxes before leaving the screen!!! I have read solutions using selectedItems or Holder class, but are not suitable for me.
I think I need to define the onClick event in the checkbox (in the AlarmAdapter), but the list of alarms is in the activity (ListAlarms), so I don't know how to "tell" the list of alarms "this is the checkbox (alarm) that has been clicked, then update its active state".
Any idea? Maybe controlling the action in the row (with OnItemClickListener) instead of clicking the checkbox?
Thanks a lot!!!
Upvotes: 0
Views: 803
Reputation: 169
This is where the custom object comes in. You create an array of these objects, and then you set a flag in the onClick event of your checkbox in the adapter. Then you can access this object and check the flag. Sorry for creating new answers, but my rep isn't high enough to comment.
Upvotes: 0
Reputation: 153
Finally, I have done a non-clean solution:
This code in the adapter:
CheckBox active = (CheckBox) view.findViewById(R.id.cb_active);
active.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
a.toggle();
boolean exists = false;
for(Alarm aux : modifiedAlarms){
if(aux.getId() == a.getId()){
exists = true;
}
}
if(!exists){
modifiedAlarms.add(a);
}
else{
//this is to guarantee that the alarm has the same state than the added one.
a.toggle();
modifiedAlarms.remove(a);
a.toggle();
}
}
});
active.setTag(a);
And this code in the activity, when leaving the screen:
ImageView back = (ImageView)findViewById(R.id.iv_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<Alarm> modified = adapter.getModifiedAlarms();
for(Alarm a : modified){
dataalarms.activeAlarm(a.getId(), a.getActive());
}
finish();
}
});
If anybody knows how to get the onClick event in the activity, it would be nice to answer here.
Thanks! :)
Upvotes: 0
Reputation: 169
I think if you read the response here you will have your answer:
How to get selected list items from a Listview with checkBox and Custom Adapter?
Upvotes: 1