getChildCount()返回不正确的孩子数量 [英] getChildCount() returns incorrect number of children
问题描述
我用X按钮创建了一个自定义TextView
,单击该按钮后其可见性设置为GONE.现在,我想获得LinearLayout
中可见的TextViews
的数量.目前,我正在获取插入的TextView总数,而不是可见的总数.
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.
示例:
当我有2个TextViews时,getChildCount()给出2个
但是如果我通过单击X按钮删除一个TextView
,它仍然会给我2.为什么会发生这种情况?
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:
这里的X是一个按钮,其onClick()会将TextView
和Button
的可见性都设置为GONE.
The X here is a button whose onClick() will set the visibility of both TextView
and the Button
to GONE.
推荐答案
如何获得可见孩子的数量?
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++;
}
}
这篇关于getChildCount()返回不正确的孩子数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!