I have the following custom view:
|--------------------|
| [ ] TextView |
|--------------------|
This is just a simple CheckBox
and a TextView
. This View
is shown multiple times (days in month), presented on the screen via a list (RecylverView
).
For that I have a Fragment
which will first read data from a database and then put this data into the list.
String[] data = getDataFromDB();
mRecycler.setAdapter(new MyAdapter(data));
Imagine that every other item has a checked CheckBox
.
So we have (for example with 4 Items) a list like this:
|--------------------|
| [ ] TextView |
|--------------------|
|--------------------|
| [X] TextView |
|--------------------|
|--------------------|
| [ ] TextView |
|--------------------|
|--------------------|
| [X] TextView |
|--------------------|
The user can now check or uncheck the CheckBox
(well, it is a checkbox :)). On programmer side the dataArray from the database must be updated too. Because, if I don't do so and the user scroll, the specific list-item should be created with the old data. Yeah, that is the recycler thing is for :)
Anyway. When the user check/uncheck I need to updated the data. And here is my question: What is the best practice to do so?
One idea is to set an Interface
in the adapter for each View
, to be notified when something changes. Each CheckBox
becomes a listener which will be called when the user clicks on a CheckBox
. The listener received a notification (from the adapter) and it can update the data.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
@Override
public void onBindViewHolder(MyViewHolder myViewHolder, int position) {
myViewHolder.myView.setModel(data.get(position));
myViewHolder.myCheckBox.setOnCheckedChangeListener(new OnChanged) {
// TODO: Update data and refresh list/adapter
}
}
}
Another idea is to put the list and the data in a custom View
.
The custom View
implements the CheckedChanceListener
and updates the database and list Adapter
.
public class TimeTrackingCardView extends CardView {
public void setListThings(String[] data, MyAdapter adapter) {
myCheckBox.setOnCheckedChangeListener(new OnChanged) {
// TODO: Update data and refresh list/adapter
}
}
}
Both ideas aren't very good. Any other ideas or patterns for refreshing Adapter
data using custom View
s?
Note:
This is a very basic custom View
. My app actually has multiple Views
(4 Buttons
with text changes, 1 CheckBox
and a EditText
) but with the same idea.