How to set scrollbar thumb programmatically in Android?

后端 未结 3 514
野趣味
野趣味 2020-12-14 11:04

I know listview can set scrollbar thumb in XML like this Android:scrollbarThumbVertical etc.

But I\'m creating a listview instance in the java code and

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 11:35

    I modified the answer to make it a method 100% programmatically

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

    }

提交回复
热议问题