Home » Android » android – How to know when GridView is completely drawn and ready?

android – How to know when GridView is completely drawn and ready?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a long GridView with custom adapter, How do I know when GridView is completely displayed and ready?

Here’s my problem in code:

dashboard = (GridView) findViewById(R.id.dashboard);
dashboard.setAdapter(new ListItemsAdapter(this, allIcons));
AlertSomeItemsOfTheListView();

in the sequence the method “AlertSomeItemsOfTheListView” is executed before the GridView is completely drawn.

How to&Answers:

You could get ViewTreeObserver instance for your GridView and use it to listen for events such as onLayout. You can get ViewTreeObserver for your View using View.getViewTreeObserver(). I am not sure if onLayout event will be enough for you as it does not exactly mean that a View is fully drawn but you can give it a try.

Here there is a code sample which you could use to listen for onLayout event (you could use such code e.g. in onCreate method of your Activity):

dashboard.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            AlertSomeItemsOfTheListView();

            // unregister listener (this is important)
            dashboard.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

Note: It is important to unregister listener after it is invoked. If you don’t do that it will be invoked on every onLayoutevent which is not what we want here (we want it to execute only once).

Answer:

When a GridView/ListView has an adapter, it calls getView when it displays items that are to be in view. If you REALLY needed to call a method after all Views are shown, you could do something like….

while(!dashboard.getAdapter().areAllItemsEnabled()){
   //wait
}

AlertSomeItemsOfTheListView();

I’m not positive that this will work, but looking at http://developer.android.com/reference/android/widget/GridView.html#getAdapter() and http://developer.android.com/reference/android/widget/ListAdapter.html make it seem like it will.