I have a layout with multiple ImageView
s, some of those images need to have the same onClickListener.
I would like my code to be flexible and to be able to get
This method provides a general way of obtaining views that match a given criteria. To use simply implement a ViewMatcher
interface
private static List getMatchingViews(ViewGroup root, ViewMatcher viewMatcher){
List views = new ArrayList();
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = root.getChildAt(i);
if (child instanceof ViewGroup) {
views.addAll(getMatchingViews((ViewGroup) child, viewMatcher));
}
if(viewMatcher.matches(child)){
views.add(child);
}
}
return views;
}
public interface ViewMatcher{
public boolean matches(View v);
}
// Example1: matches views with the given tag
public class TagMatcher implements ViewMatcher {
private String tag;
public TagMatcher(String tag){
this.tag = tag;
}
public boolean matches(View v){
String tag = v.getTag();
return this.tag.equals(tag);
}
}
// Example2: matches views that have visibility GONE
public class GoneMatcher implements ViewMatcher {
public boolean matches(View v){
v.getVisibility() == View.GONE
}
}