dimanche 6 septembre 2015

Best practise to refreshing adapter data over custom view

I have the following custom view: |--------------------| | [ ] TextView | |--------------------| This is just a simple CheckBox and a TextView. This view must be multiple times (days in month) presented on the screen via a list (RecylverView).

For that I have a Fragment which will be first read data from a database and then put these data to the list.

String[] data = getDataFromDB();
mRecycler.setAdapter(new MyAdapter(data));

Image that all second item have 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 practise to do so?

One idea is to set an Interface in the adapter on each View to be notificated when something changed. Each CheckBox became a listener which will be called when the user clicks on a CheckBox. The listener received a notification (to 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 to the custom view. The custom view implements the CheckedChanceListener and updated the data and list.

public class TimeTrackingCardView extends CardView {

    public void setListThings(String[] data, MyAdapter adapter) {
        myCheckBox.setOnCheckedChangeListener(new OnChanged) {
            // TODO: Update data and refresh list/adapter
        }
    }

}

Booth ideas aren't very well. So any other ideas or patterns to refreshing adapter data over custom view?

For explanation: This is a very easy custom view. My app has in real multiple views (4 Buttons with text changes, 1 CheckBox and a EditText) but with the same idea.




Aucun commentaire:

Enregistrer un commentaire