Find all views with tag?

后端 未结 4 708
臣服心动
臣服心动 2020-11-29 06:12

I am looking to find all the views in a specified activity that have the tag \"balloon\" for example then hide them using setVisibility to GONE.

相关标签:
4条回答
  • You could set tags to your views in this way:

    someView.setContentDescription("MyTag");
    

    And then in order to find all views with that tag you need to call:

    ArrayList<View> outputViews = new ArrayList<>();
    rootView.findViewsWithText(outputViews, "MyTag", FIND_VIEWS_WITH_CONTENT_DESCRIPTION); 
    
    0 讨论(0)
  • 2020-11-29 06:59

    Could this API call View#findViewWithTag help? Please note that it only returns one view...

    Look for a child view with the given tag. If this view has the given tag, return this view.

    0 讨论(0)
  • 2020-11-29 07:02

    One approach would be to start with the parent ViewGroup, loop through its children(and their children and so on) and then check tags on each one of them.

    0 讨论(0)
  • 2020-11-29 07:09

    Here you go:

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

    I've already answered it here :Android - how to find multiple views with common attribute

    0 讨论(0)
提交回复
热议问题