Home » Android » android – How do I check when my ListView has finished redrawing?

android – How do I check when my ListView has finished redrawing?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a ListView. I updated its adapter, and call notifydatasetchanged(). I want to wait until the list finishes drawing and then call getLastVisiblePosition() on the list to check the last item.

Calling getLastVisiblePosition() right after notifydatasetchanged() doesn’t work because the list hasnt finished drawing yet.

How to&Answers:

Hopefully this can help:

  • Setup a addOnLayoutChangeListener on the listview
  • Call .notifyDataSetChanged();
  • This will fire off the OnLayoutChangeListener once completed
  • Remove the listener
  • Perform code on update (getLastVisiblePosition())

    mListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    
      @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        mListView.removeOnLayoutChangeListener(this);
        Log.e(TAG, "updated");
      }
    });
    
    mAdapter.notifyDataSetChanged();
    

Answer:

You can implement callback, after the notifyDataSetChanged() it will be called and do the job you need. It means the data has been loaded to the adapter and at next draw cycle will be visible on the GUI. This mechanism is built-in in Android. See DataSetObserver.

Implement his callback and register it into the list adapter, don’t forget to unregister it, whenevr you no longer need it.

/**
 * @see android.widget.ListAdapter#setAdapter(ListAdapter)
 */
@Override
public void setAdapter(android.widget.ListAdapter adapter) {
    super.setAdapter(adapter);

    adapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            onListChanged();
            // ... or do something else here...
            super.onChanged();
        }
    });
}