Thomas Roulin Thomas Roulin - 10 days ago 5
Android Question

When does the ListView items have been drawn to the screen

I want to know when the

ListView
layout is created. I need to perform an action on the item views, for that I need to know when the layout has been drawn to the screen. I need to get the IDs of the created views.

Is there a way to know when this is done ?

Edit (precision):


  • Calling right after the
    ListView,notifyDataSetChanged
    doesnt work,
    ListView.getChildCount
    still returns
    0
    .

  • I display a limited number of items, all items are displayed on the screen.


Sid Sid
Answer

In order to gett all the IDs from the view I've tried the following

private List<View> mChildren;

I've declared a List of View which will contain all the children and then I managed to get all the children with the following snippet

ViewTreeObserver obs = mListView.getViewTreeObserver();
obs.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        for(int index = 0; index<((ViewGroup)mListView).getChildCount(); ++index) {
            View nextChild = ((ViewGroup)mListView).getChildAt(index);
            if(!mChildren.contains(nextChild)){
                mChildren.add(nextChild); //New Child to add
            }

        }
    }
});

And then you can you mChildren which contain all the children views. Otherwhise you can also check onFinishInflate. Hope it helps :)

Update

As me and Thomas were discussing in chat, I came back to memory that also onViewAdded (from API 23) can be useful.

Comments