2012-03-15 94 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(); 
    } 

}

相關問題