getChildCount() returns incorrect number of children

南楼画角 提交于 2019-12-30 11:10:07

问题


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 LinearLayout. Currently, I am getting the count of total TextViews inserted rather than the visible ones.

Example:

When I have 2 TextViews, getChildCount() gives 2 but if I delete one TextView by clicking the X button, it still gives me 2. Why is this happening?

I have created something like this:

The X here is a button whose onClick() will set the visibility of both TextView and the Button to GONE.


回答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/pseudocode
int visibleChildren = 0;
for (int i = 0; i < layout.getChildCount(); i++) {
    if (layout.getChildAt(i).getVisibility() == View.VISIBLE) {
        visibleChildren++;
    }
}


来源:https://stackoverflow.com/questions/17526350/getchildcount-returns-incorrect-number-of-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!