如果您只需要支持 API 24 或更高版本,则可以使用自定义 drawable 来完成此任务。您需要决定如何允许可绘制对象与活动进行通信。这是一种可能的解决方案。
res/drawable/my_custom_scrollbar_thumb.xml
<com.example.RegisteredMutableDrawable android:id="@+id/scroll_thumb" />
res/drawable/my_custom_scrollbar_track.xml
<com.example.RegisteredMutableDrawable android:id="@+id/scroll_track" />
在你的布局文件中的某个地方
<ListView android:scrollbarTrackVertical="@drawable/my_custom_scrollbar_track" android:scrollbarThumbVertical="@drawable/my_custom_scrollbar_thumb"
可绘制的实现
public class RegisteredMutableDrawable extends DrawableWrapper
{
public static interface Registrar
{
public void register(int _id, RegisteredMutableDrawable _drawable);
}
public static Registrar registrar;
private static int[] ATTRS = new int[] { android.R.attr.id };
public RegisteredMutableDrawable()
{
super(null);
}
public void inflate(Resources _res, XmlPullParser _parser, AttributeSet _as, Theme _theme)
throws XmlPullParserException, IOException
{
super.inflate(_res, _parser, _as, _theme);
final Registrar r = registrar;
if (r != null)
{
final TypedArray ta = _res.obtainAttributes(_as, ATTRS);
final int id = ta.getResourceId(0, 0);
ta.recycle();
r.register(id, this);
}
}
}
在你的活动中
public class MyActivity extends Activity implements RegisteredMutableDrawable.Registrar
{
@Override public void onCreate(Bundle _icicle)
{
super.onCreate(_icicle);
RegisteredMutableDrawable.registrar = this;
setContentView(R.layout.whatever);
RegisteredMutableDrawable.registrar = null; // don't leak our activity!
}
@Override public void register(int _id, RegisteredMutableDrawable _drawable)
{
switch(_id)
{
case R.id.scroll_thumb:
_drawable.setDrawable(myThumbDrawable);
break;
case R.id.scroll_track:
_drawable.setDrawable(myTrackDrawable);
break;
}
}
}