问题:
因为使用了哔哩哔哩的主题框架,所以需要动态修改RecyclerView的scrollbar颜色,但是scrollbar是view的私有内部类,只能在xml中配置。如下图
image解决方法:
查看源码,通过反射获取scrollbar的drawable,然后用框架着色
public static void tintScrollbarColor(Context context, RecyclerView recyclerView) {
try {
//通过反射一层层的获取对象,直到获取到进度条
Class<View> clazz = View.class;
Method method = clazz.getDeclaredMethod("getScrollCache");
method.setAccessible(true);
Object scrollabilityCacheObj = method.invoke(recyclerView);
Class<?> scrollabilityCacheClazz = scrollabilityCacheObj.getClass();
Field scrollBarField = scrollabilityCacheClazz.getField("scrollBar");
Object scrollbarObj = scrollBarField.get(scrollabilityCacheObj);
Class<?> scrollbarClass = scrollbarObj.getClass();
Field mVerticalThumbField = scrollbarClass.getDeclaredField("mVerticalThumb");
Field mHorizontalThumbField = scrollbarClass.getDeclaredField("mHorizontalThumb");
mVerticalThumbField.setAccessible(true);
mHorizontalThumbField.setAccessible(true);
Drawable mVerticalThumb = (Drawable) mVerticalThumbField.get(scrollbarObj);
Drawable mHorizontalThumb = (Drawable) mHorizontalThumbField.get(scrollbarObj);
//对显示的drawable着色
Drawable mVerticalThumbTint = ThemeUtils.tintDrawable(mVerticalThumb,
ThemeUtils.getColorById(context, R.color.theme_color_primary));
Drawable mHorizontalThumbTint = ThemeUtils.tintDrawable(mHorizontalThumb,
ThemeUtils.getColorById(context, R.color.theme_color_primary));
//设置新的drawable
mVerticalThumbField.set(scrollbarObj, mVerticalThumbTint);
mHorizontalThumbField.set(scrollbarObj, mHorizontalThumbTint);
} catch (Exception e) {
e.printStackTrace();
}
}
网友评论