Updated 26 October 2021
While making dynamic views in your android application, we often feel the need to find all the views containing a particular keyword in Tag, associated with the view itself so that we can perform some action on all of the views later.In this blog, we will learn how to Find all the views containing a particular keyword in Tag.
Implementing this is super easy, all you need to know is familiarity with the lists and recursion. The simple plain logic of adding to the list will get you the desired result.
That’s it conceptually you have obtained the desired result. Let’s have a look at the code.
Function to get all the views:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private static ArrayList<View> getViewsByTag(ViewGroup root, String tagKey ){ 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, tagKey)); } final Object tagObj = child.getTag(); if (tagObj != null && tagObj.toString().contains(tagKey)) { views.add(child); } } return views; } |
Using it in your code :
1 2 3 4 5 6 7 |
ArrayList<View> views = getViewsByTag(my_root_view,"my_tag"); for (View view: views) { view.setVisibility(View.GONE); // Add Your Logic Here } // REPLACE my_root_view with your view whose all childs you want to search // REPLACE my_tag with your tag keyword, you want to use for searching |
That’s All.
Keep coding and Keep Sharing
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.