2012-03-15 91 views

回答

2

我不知道这个问题的答案,但经过一番探索后,我不认为没有一丝麻烦就没有可能。

此xml属性实际上与View相关联,而不是ListView - 在Android View源代码中,它似乎唯一设置可绘制垂直拇指的地方是'initializeScrollbars'方法。现在这个方法不是私有的,所以我们可以扩展View的任何子类并覆盖这个方法,但问题在于设置可绘制的缩略图的关键组件ScrollabilityCache是​​私有的,没有任何getter方法。

因此,如果不重写很多代码,我不认为有任何简单的方法来做到这一点 - 对不起!

+0

谢谢你的调查:) – dreamtale 2012-05-09 05:46:18

21

可以实现经由反射:

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)); 
+5

这应该是被接受的答案。 – Dogcat 2016-04-29 07:23:16

+1

嗨,@ Eng.Fouad上面的解决方案不工作在recyclerview..even /*listview.mScrollCache.scrollBar.setVerticalThumbDrawable(getResources().getDrawable(R.drawable.scrollbar_style))*/这行不能用于listview或recyclerview。 – 2017-10-12 12:02:30

1

我修改的答案,使之的方法100%编程

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(); 
    } 

}

相关问题