|
18 | 18 |
|
19 | 19 | import android.content.Context; |
20 | 20 | import android.os.Build; |
| 21 | +import android.support.annotation.IdRes; |
21 | 22 | import android.util.LayoutDirection; |
22 | 23 | import android.util.TypedValue; |
23 | 24 | import android.view.View; |
| 25 | +import android.view.ViewGroup; |
24 | 26 |
|
25 | 27 | import java.lang.reflect.ParameterizedType; |
26 | 28 |
|
@@ -57,4 +59,33 @@ static boolean isRightToLeft(Context c) { |
57 | 59 | static <T> String getGenericName(T object) { |
58 | 60 | return ((Class<T>) ((ParameterizedType) object.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getSimpleName(); |
59 | 61 | } |
| 62 | + |
| 63 | + /** |
| 64 | + * Like findViewById(), but traverses upwards from the view given instead of downwards, |
| 65 | + * ignores the view itself and its direct ascendants, and prefers siblings of the initial |
| 66 | + * view over the siblings of one of its ascendants. |
| 67 | + * |
| 68 | + * @param id the id to search for. |
| 69 | + * @param viewToStartFrom the view whose siblings (and whose parents' siblings) should be searched. |
| 70 | + * @return the view found, or null if none could be located. |
| 71 | + */ |
| 72 | + static View findNearestNeighborWithID(@IdRes int id, View viewToStartFrom) { |
| 73 | + if (viewToStartFrom == null) return null; |
| 74 | + |
| 75 | + ViewGroup parent; |
| 76 | + try { |
| 77 | + parent = (ViewGroup) viewToStartFrom.getParent(); |
| 78 | + } catch (ClassCastException e) { |
| 79 | + return null; |
| 80 | + } |
| 81 | + for (int i = 0; i < parent.getChildCount(); i++) { // Checks the children of the given view's parent |
| 82 | + if (viewToStartFrom == parent.getChildAt(i)) continue; // Excluding the given view itself |
| 83 | + View result = parent.getChildAt(i).findViewById(id); |
| 84 | + if (result != null) { |
| 85 | + return result; |
| 86 | + } |
| 87 | + } |
| 88 | + return findNearestNeighborWithID(id, parent); // If the view could not be found, check the next higher generation |
| 89 | + } |
| 90 | + |
60 | 91 | } |
0 commit comments