13

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.

Fahim
  • 12,198
  • 5
  • 39
  • 57
ha1ogen
  • 13,375
  • 3
  • 19
  • 19

3 Answers3

48

Hopefully this can help:

  • Setup an addOnLayoutChangeListener on the listview
  • Call .notifyDataSetChanged();
  • This will fire off the OnLayoutChangeListener when completed
  • Remove the listener
  • Perform code on update (getLastVisiblePosition() in your case)

    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();
    
Petro
  • 3,484
  • 3
  • 32
  • 59
3

I think this implementation can solve the problem.

    // draw ListView in UI thread
    mListAdapter.notifyDataSetChanged();
    
    // enqueue a message to UI thread
    mListView.post(new Runnable() {
        @Override
        public void run() {
            // this will be called after drawing completed
        }
    });
tuantv.dev
  • 108
  • 7
0

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();
        }
    });
}
technik
  • 1,009
  • 11
  • 17