Skip to content Skip to sidebar Skip to footer

Getchildcount() Returns Incorrect Number Of Children

I have created a custom TextView with an X button, whose visibility are set to GONE when the button is clicked. Now I want to get the number of visible TextViews in the LinearLayou

Solution 1:

how can I get the count of the visible children?

Well for that you need to iterate over the children of the view/layout and check the visibility. It is a simple loop:

// untested/pseudocodeint visibleChildren = 0;
for (int i = 0; i < layout.getChildCount(); i++) {
    if (layout.getChildAt(i).getVisibility() == View.VISIBLE) {
        visibleChildren++;
    }
}

Solution 2:

Rather late to problem posted. Don't think the answers addressed the problem correctly. A few years since the problem of "getChildCount under reporting visible items displayed" was reported, yet my research found no one had fingered out what was causing this problem surfacing in some circumstances.

I had the same problem recently which led me to investigate further. Here's my discovery.

Say if 9 items on RecyclerView are visible. Call getChildCount(). It should return 9, maybe 1 or 2 less/more depending on partially visible items at the top and bottom. This will be the result most of the time ... until the soft keyboard shows for some TextEdit input. If you call getChildCount() about 500 msecs after the method call that led to showing the keyboard, the result will be less than 9. It will be the count of items unobstructed by the keyboard view. Weird, even though user didn't change the displayed contents of the RecyclerView. What's weird too is that even after the keyboard is dismissed, and all 9 items are again visible, calling getChildCount() will still return the incorrect under count! This happened with Android 11, and presumably with pre-11s (didn't test with post-11s).

A clue to solving this is the method RecyclerView.postInvalidateDelayed. If you really need to have the correct getChildCount number to work with, do something like this (after the keyboard is dismissed):

myRecyclerView.invalidate();
myRecyclerView.postDelayed(myRunnable, 200); 

Subtle problem!

Post a Comment for "Getchildcount() Returns Incorrect Number Of Children"