I want to implement a CheckBox
on a RecyclerView.Adapter
But I don't know where to start right, I have previously read references from several articles related to the CheckBox
on the RecyclerView
but there are no articles that match my problem.
I have a response from an API like this :
{
"results": [
{
"isNameChecked": false,
"name": "Data A",
"data": [
{
"isChecked": false,
"id": "A1",
"name": "Data 1"
},
{
"isChecked": true,
"id": "A2",
"name": "Data 2"
}
]
},
{
"isNameChecked": true,
"name": "Data B",
"data": [
{
"isChecked": true,
"id": "B1",
"name": "Data 1"
},
{
"isChecked": true,
"id": "B2",
"name": "Data 2"
},
{
"isChecked": true,
"id": "B3",
"name": "Data 2"
}
]
}
]
}
If the CheckBox
All is true
, all the existing CheckBox
will be set true
(isNameChecked
and isChecked
) automatically and save the id
(A1
, A2
, B2
, etc.) if the id
is true from data
into a Variable
Otherwise, if the All
box is false, but isNameChecked
set true, the data
in the result will update isChecked
as true
I don't know how you're displaying your checkboxes, but your adapter should have the data for all the items stored in it, and part of that data is whether the item is checked or not. I think you have two approaches:
Make the All
checkbox set/unset the checked status of all its child items (i.e. iterate through your list, map or whatever and change all the values) and then call notifyDataSetChanged()
(or another notify
method) so the display updates
Don't change the children's checked states (so if you uncheck All
, the others "remember" if they were checked or not) and just decide whether they should display as checked based on the top-level boxes
In your adapter's onBindViewHolder
method (where it sets up the display for an item, including whether it shows as checked or not) you can find the parent checkbox, and if it's checked you can display the child as checked too. Otherwise show its actual state (the real value set in the data).
That's just the basic idea, you'll have to work out how to fit it in with what you're actually doing and how you're representing that hierarchy in your data, but it's one way you can approach it!