V
V
Vermut7562017-01-29 08:36:06
Java
Vermut756, 2017-01-29 08:36:06

Do I understand Adapter, notifyDataSetChanged and the purpose of the ViewHolder pattern correctly?

Given: some ArrayList with several objects of the same type, and an Adapter inherited from ArrayAdapter that will present these objects in the ListView.
Required: to update a specific object, and accordingly update the corresponding View in the ArrayAdapter.
I did it like this:

arrayList.get(...).setMyProperty(...);
adapter.NotifyDataSetChanged();

True, at first for some reason it did not work - the View was not updated.
I thought that this is due to the fact that the adapter somehow compares objects, and they do not have a correct comparison mechanism , does not detect changes and does not update the corresponding View, and it is necessary to implement something like hashCode, equals or comparable in these objects then it will work correctly.
But I found the solution easier - just add the following to your ArrayAdapter implementation:
@Override
    public int getCount() {
    	return values.size();
    }

As a result, the element began to be updated.
But after all, I still do not have a comparison mechanism, which means that when updating one element, it will stupidly be called getView()for all elements.
Do I understand correctly that this will be the case? (I’ll check a little later, it’s just that there is only 1 element for now)
If I understand correctly, is this normal, or can (should) I somehow implement a comparison so that getView is called only for views of updated objects?
Also, as I understand it, there is a pattern ViewHolderthat allows in this case to get rid of inflate() and findViewById() each time each element is updated, thereby, although not abandoning getView for all elements, but optimizing it.
But isn't it better not to call getView at all once again, but only for updated elements?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-01-30
@zagayevskiy

Of course better. But in the foliage there is no way to do this without crutches. Yes, you don’t need to use leaves, take RecyclerView right away. There is a set of methods exactly what you want. And just forget the leaves.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question