我是 android 新手,现在我正试图找到一种方法来获取控件的数量(我不知道如何在 android 中调用这些控件,我的意思是我有 4 个文本视图、2 个编辑文本、3 个按钮等等我总共有 9 个“控件”),有没有办法计算它们?
问问题
139 次
1 回答
3
它们在 Android 中称为视图。是的,甚至是按钮。您可以使用 getChildCount() 但如果您在视图中有视图,则必须递归地执行此操作。我要做的是获取您的基本视图,然后使用以下内容:
public int getViewCount(View view) {
int viewCount = 1;
if(view instanceof ViewGroup) {
viewCount += countChildren((ViewGroup)view);
}
return viewCount;
}
public int countChildren(ViewGroup viewGroup) {
int viewCount = 0;
for(int i = 0; i < viewGroup.getChildCount(); i++){
viewCount += getViewCount(viewGroup.getChildAt(i));
}
return viewCount;
}
使事情复杂化的事实是,只有 ViewGroup 可以有孩子,但 Button 和其他东西是 View 的实例,而不是 ViewGroup 的实例。
如果您不希望它计算 ViewGroups,请尝试以下操作:
public int getViewCount(View view) {
int viewCount = 1;
if(view instanceof ViewGroup) {
viewCount = 0; // Uncounts for ViewGroups, but still checks them for Views.
viewCount += countChildren((ViewGroup)view);
}
return viewCount;
}
public int countChildren(ViewGroup viewGroup) {
int viewCount = 0;
for(int i = 0; i < viewGroup.getChildCount(); i++){
viewCount += getViewCount(viewGroup.getChildAt(i));
}
return viewCount;
}
于 2013-05-17T04:19:36.717 回答