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

Android 如何查找具有特定标记(属性)的视图列表,android,android-layout,Android,Android Layout,我为UI小部件设置了标签,我想检索一个具有特定标签的视图列表。使用View.findViewWithTag(“测试标签”)只返回一个视图,而不是所有支持标签的视图 非常感谢您的帮助。您不应该期望此方法提供一个视图数组,因为方法签名本身告诉您它将返回一个视图 public final View findViewWithTag (Object tag) 但是,您可以做的是将布局设置为ViewGroup,然后通过查找所有子视图的标记来迭代所有子视图,以找到所需的视图。例如: /** * Get

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


非常感谢您的帮助。

您不应该期望此方法提供一个视图数组,因为方法签名本身告诉您它将返回一个视图

public final View findViewWithTag (Object tag) 
但是,您可以做的是将布局设置为
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;
}
/**
*递归获取与给定标记匹配的所有视图
*@param根父视图。例如,布局
*@param标记要查找的标记
*@返回视图列表
*/
公共静态列表递归查找视图WithTag(视图组根,对象标记){
List allview=new ArrayList();
final int childCount=root.getChildCount();
对于(inti=0;i
inttags=6;
for(int index=0;index

希望这对其他人有所帮助!

在我的用例中,这非常简单。例如,一个布局中有12个带有相同标记的ImageView。 当findViewWithTag(“image”)调用时。它将从布局中简单地给出第一个索引single imageview。解决方案很简单,当您获得带有该标记的imageview时,只需将该imageview标记设置为空字符串。下次在迭代中,当findViewWithTag(“image”)调用时。它将简单地给出下一个imageview

for(int inf = 0; inf < albumPageImagesInfoList.get(cardPosition); inf++){
            ImageView imageView = inflateView.findViewWithTag("image");
            if(imageView!=null){
                imageView.setId(uivid);
                imageView.setTag("");
                imgIndexId++;
            }
        }    
for(int-inf=0;inf
我知道该方法只返回一个视图。我正在寻找一种获取所有视图的简单方法。我认为迭代一个视图组并不是一个优化的解决方案。你怎么知道它不是一个优化的解决方案呢?我不清楚,优化是相对的,所以如果找不到更好的解决方案,它可以优化。我知道这种方法,但我不想使用它出于某些原因,请使用它。但最后,如果没有更好的解决方案,我将接受您的答案。同样需要递归方法,我自己编写,但为了更好地回答,请提供。waqas我有一个类似的问题。您能告诉我怎么做吗?请参阅:
for(int inf = 0; inf < albumPageImagesInfoList.get(cardPosition); inf++){
            ImageView imageView = inflateView.findViewWithTag("image");
            if(imageView!=null){
                imageView.setId(uivid);
                imageView.setTag("");
                imgIndexId++;
            }
        }