本文介绍了如何查找具有特定标签的视图列表(属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I set tag for UI widgets and I want to retrieve a list of View that has a specific tag. Using View.findViewWithTag("test_tag") just return one View not all view that support tag.

任何帮助表示赞赏.

推荐答案

您不应该期望此方法有一组视图,因为方法签名本身告诉我们它将返回一个视图.

You shouldnt expect an array of views from this method, since the method signature itself tells that it will return a single view.

public final View findViewWithTag (Object tag)

但是,您可以做的是将布局设为ViewGroup,然后遍历所有子视图以通过在其子标签上进行查找来找到所需的视图.例如:

However, what you may do is to get your layout as ViewGroup and then iterate through all the child views to find out your desired view by doing a look-up on their tag. For example:

/**
 * 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;
}

这篇关于如何查找具有特定标签的视图列表(属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:14