问题
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.
回答1:
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).
回答2:
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.
来源:https://stackoverflow.com/questions/14119128/how-to-know-when-gridview-is-completely-drawn-and-ready