使用标签android查找元素

时间:2016-07-18 05:28:28

标签: android

我需要在我的活动中使用其标记找到一个视图元素。我尝试获取根视图并使用该根视图使用标记查找所需元素,但它始终返回null。

任何帮助表示赞赏!!

1 个答案:

答案 0 :(得分:0)

private static ArrayList<View> getViewsByTag(ViewGroup root, String tag){
ArrayList<View> views = new ArrayList<View>();
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
    final View child = root.getChildAt(i);
    if (child instanceof ViewGroup) {
        views.addAll(getViewsByTag((ViewGroup) child, tag));
    } 

    final Object tagObj = child.getTag();
    if (tagObj != null && tagObj.equals(tag)) {
        views.add(child);
    }

} return views;

}

这不是我的代码,我发现它是&#34; stackoverflow&#34;当我遇到类似的问题时。