Skip to content

Commit 3271f76

Browse files
committed
Fixes #119
1 parent 4f3425b commit 3271f76

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

lib/src/main/java/com/turingtechnologies/materialscrollbar/MaterialScrollBar.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,14 @@ protected void onAttachedToWindow() {
221221
attached = true;
222222

223223
if(seekId != 0) {
224-
recyclerView = getRootView().findViewById(seekId);
224+
try {
225+
recyclerView = (RecyclerView) Utils.findNearestNeighborWithID(seekId, this);
226+
if (recyclerView == null) {
227+
throw new RuntimeException("The id given for the recyclerView did not refer to a sibling of the bar or one of its ascendants");
228+
}
229+
} catch (ClassCastException e) {
230+
throw new RuntimeException("The id given for the recyclerView did not refer to a RecyclerView", e);
231+
}
225232
generalSetup();
226233
}
227234
}

lib/src/main/java/com/turingtechnologies/materialscrollbar/Utils.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@
1818

1919
import android.content.Context;
2020
import android.os.Build;
21+
import android.support.annotation.IdRes;
2122
import android.util.LayoutDirection;
2223
import android.util.TypedValue;
2324
import android.view.View;
25+
import android.view.ViewGroup;
2426

2527
import java.lang.reflect.ParameterizedType;
2628

@@ -57,4 +59,33 @@ static boolean isRightToLeft(Context c) {
5759
static <T> String getGenericName(T object) {
5860
return ((Class<T>) ((ParameterizedType) object.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getSimpleName();
5961
}
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+
6091
}

0 commit comments

Comments
 (0)