0

I'm populating a GridView wth an AsyncTask:

@Override
public void onLoad() {
    super.onLoad();
    //... set Loading view and actually get the data
    adapter = new DepartmentGridAdapter(getActivity(), R.layout.gird_department_item_layout,
            mSalesPresenter.getDepartments());
}

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView
    onShowTutorial(); // <--- This is where I need to get the firstChild.
}

After the AsyncTask is done, I just need to access the firstChild of the GridView:

@Override
public void onShowTutorial() {
    if (gridView.getChildAt( gridView.getFirstVisiblePosition())!= null )
        // ... doStuff
}

But the statement is Always null. I even call getCount for the GridView and it's not 0. The problem seems that the GridView childs are not accesible right away. If i Use a button to force the execution of the method onShowTutorial() after the UI is ready then I can access the first child.

I'm running out of ideas to trigger the method after the execution of the thread.

Any solution?

chntgomez
  • 2,058
  • 3
  • 19
  • 31

2 Answers2

1

Try to post a runnable to be run when the gridView is done doing what it is currently doing (more info regarding View.post() here) :

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView

    // Tells the gridView to "queue" the following runnable
    gridView.post(new Runnable() {
        @Override
        public void run() {
            onShowTutorial(); // <--- This is where I need to get the firstChild.
        }
    });
}
Community
  • 1
  • 1
mVck
  • 2,910
  • 2
  • 18
  • 20
0

Found it.

I used a ViewTreeObserver and it works:

gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            onShowTutorial();
        }
    });
chntgomez
  • 2,058
  • 3
  • 19
  • 31