我知道在XML中可以这样设置listview滚动条的滑块:Android:scrollbarThumbVertical
等等。
但是我正在Java代码中创建一个listview实例,可能需要设置不同的滚动条滑块。有没有一种方法可以通过编程的方式来设置滑块?
您可以通过反射实现:
try
{
Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
mScrollCacheField.setAccessible(true);
Object mScrollCache = mScrollCacheField.get(listview);
Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
scrollBarField.setAccessible(true);
Object scrollBar = scrollBarField.get(mScrollCache);
Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
method.setAccessible(true);
method.invoke(scrollBar, getResources().getDrawable(R.drawable.scrollbar_style));
}
catch(Exception e)
{
e.printStackTrace();
}
上述代码执行方式为:
listview.mScrollCache.scrollBar.setVerticalThumbDrawable(getResources().getDrawable(R.drawable.scrollbar_style));
public static void ChangeColorScrollBar(View Scroll, int Color, Context cxt){
try
{
Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
mScrollCacheField.setAccessible(true);
Object mScrollCache = mScrollCacheField.get(Scroll);
Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
scrollBarField.setAccessible(true);
Object scrollBar = scrollBarField.get(mScrollCache);
Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
method.setAccessible(true);
Drawable[] layers = new Drawable[1];
ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
sd1.getPaint().setColor(cxt.getResources().getColor(Color));
sd1.setIntrinsicWidth(Math.round(cxt.getResources().getDimension(R.dimen.dp_3)));
layers[0] = sd1;
method.invoke(scrollBar, layers);
}
catch(Exception e)
{
e.printStackTrace();
}
}
View
相关,而不是ListView
。在Android View源代码中,似乎唯一设置垂直滑块图像的地方是'initializeScrollbars'方法。现在,这个方法不是私有的,所以我们可以扩展View的任何子类并覆盖此方法,但问题在于一个关键组件(ScrollabilityCache)需要设置拇指图像,它是私有的,没有任何getter方法。从Android Q(API级别29)开始,您可以使用setVerticalScrollbarThumbDrawable()
和setHorizontalScrollbarThumbDrawable()
:
scrollView.verticalScrollbarThumbDrawable =
ResourcesCompat.getDrawable(resources,
R.drawable.scrollview_thumb, null)
java.lang.NoSuchMethodException: android.widget.ScrollBarDrawable.setVerticalThumbDrawable [class android.graphics.drawable.Drawable]
。 - Prof