Neigaard February 2016

RecyclerView not updating its views when updated with new data

I have a RecyclerView with a RecyclerView.Adapter implementation, which has a list of objects plus a header and a footer view, and I am switching on the viewType to show header for position 0 and footer for position getItemCount() (my "getItemCount()" implementation returns "data.size() + 2" to accommodate for header and footer). This all works great, the header and foot are shown at the correct places, but when I reach the end of the list and the footer is shown, I load more data and add that to my "data" list, and then I want the footer view to be replaced with the next loaded data view, but this does not happen. I have tried with alle the different "notifyX" methods on the adapter, but it seems that it does not get updated until i scroll the list (and then it all works as I want).

What am I missing here? How do I force the RecyclerView to redraw the last element in the list?

My adapter:

private class TransactionsAdapter extends RecyclerView.Adapter {
        private List transactions;

        private static final int TYPE_HEADER = 0;
        private static final int TYPE_ITEM = 1;
        private static final int TYPE_FOOTER = 2;

        private TransactionsAdapter(List transactions) {
            this.transactions = transactions;
        }

        public void add(Transaction transaction) {
            transactions.add(transaction);
            notifyItemInserted(transactions.size());
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if(viewType == TYPE_HEADER) {
                ViewHolder vh = new ViewHolder(inflate(getContext(), R.layout.postings_list_header, null), TYPE_HEADER);
                return vh;
            } else if(viewType == TYPE_FOOTER) {
                ViewHolder vh = new ViewHolder(inflate(getContext(), R.layout.postings_list_footer, null), TYPE_FOOTER);
                return vh;
            }
            SlidingCellView cellView = new        

Answers


Gustavo February 2016

You can add to onBindViewHolder:

        if (position == getItemCount() - 1) {
            // request more transactions
        }

Then your callback calls the add method, that should call notifyDataSetChanged:

    public void add(Transaction transaction) {
        transactions.add(transaction);
        notifyDataSetChanged();
    }

There is a working example without footer here.

If you need a good library to easily handle header/footers in your RecyclerView you should try SectionedRecyclerViewAdapter.

Post Status

Asked in February 2016
Viewed 1,717 times
Voted 8
Answered 1 times

Search




Leave an answer