如何查找具有特定标记(属性)的视图列表

Beh*_*nam 9 android android-layout

我为UI小部件设置了标签,我想检索具有特定标签的View列表.使用View.findViewWithTag("test_tag")只返回一个View并非所有支持tag的视图.

任何帮助赞赏.

waq*_*lam 15

你不应该期望这个方法有一个视图数组,因为方法签名本身告诉它将返回一个视图.

public final View findViewWithTag (Object tag) 
Run Code Online (Sandbox Code Playgroud)

但是,您可能要做的是获取布局ViewGroup,然后遍历所有子视图,通过查找其标记来查找所需的视图.例如:

/**
 * Get all the views which matches the given Tag recursively
 * @param root parent view. for e.g. Layouts
 * @param tag tag to look for
 * @return List of views
 */
public static List<View> findViewWithTagRecursively(ViewGroup root, Object tag){
    List<View> allViews = new ArrayList<View>();

    final int childCount = root.getChildCount();
    for(int i=0; i<childCount; i++){
        final View childView = root.getChildAt(i);

        if(childView instanceof ViewGroup){
          allViews.addAll(findViewWithTagRecursively((ViewGroup)childView, tag));
        }
        else{
            final Object tagView = childView.getTag();
            if(tagView != null && tagView.equals(tag))
                allViews.add(childView);
        }
    }

    return allViews;
}
Run Code Online (Sandbox Code Playgroud)