因为scrollbar是view的私有内部类,所以需要动态修改RecyclerView的scrollbar颜色, 只能通过反射获取scrollbar的drawable,然后用反射着色,亲测可用,代码直接粘贴就可使用。
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ScrollBarUtil {
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 = tintDrawable(mVerticalThumb, Color.parseColor("#6694FF"));
Drawable mHorizontalThumbTint = tintDrawable(mHorizontalThumb, Color.parseColor("#6694FF"));
//设置新的drawable
mVerticalThumbField.set(scrollbarObj, mVerticalThumbTint);
mHorizontalThumbField.set(scrollbarObj, mHorizontalThumbTint);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Drawable tintDrawable(@NonNull Drawable drawable, int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrappedDrawable, color);
return wrappedDrawable;
}
public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(wrappedDrawable, colors);
return wrappedDrawable;
}
public static int getColorById(Context context, int color) {
return context.getResources().getColor(color);
}
}