Tony Lin Tony Lin - 10 months ago 67
Android Question

Android ListView, need to call getChildAt(index) but always return null unless wait some times

I am new to Android.

I have to update a ListView with chatAdapter.notifyDataSetChanged();

Everything works as expected, ListView is updated.

Then I need to call ListView getChildAt(index), however it is always null, unless I wait for some times

Here is code snippet below:

if (requestType == RequestType.FirstRequest){
if (chatMessages.size() != 0) {
//scroll to bottom
chatListView.setSelection(chatMessages.size() - 1);

Log.i(TAG, "" + chatListView.getChildAt(0));
new Handler().postDelayed(new Runnable() {
public void run() {
Log.i(TAG, "" + chatListView.getChildAt(0));
}, 3000);

The first Log always returns null, however, I am able to get child if I wait 3 seconds.
It seemed that after I called chatAdapter.notifyDataSetChanged(), it took some time to inflate those child views.
How do I properly call getChildAt(index) in this case?

Answer Source Runnable(){

    public void run(){
        //your code to execute after list redraw

Runnable passed to post method will be excecuted after all pending operations of ListView (or any other View). in this case - list redrawing