我的自定义Drawable
是这样的:
public class SeekBarBackgroundDrawable extends Drawable {
Paint mBasePaint = null;
public SeekBarBackgroundDrawable() {
super();
mBasePaint = new Paint();
mBasePaint.setAntiAlias(true);
mBasePaint.setStyle(Paint.Style.STROKE);
mBasePaint.setStrokeCap(Paint.Cap.ROUND);
mBasePaint.setStrokeWidth(10);
mBasePaint.setColor(0xFF00FF00);
}
@Override
public void draw(Canvas canvas) {
Rect r = getBounds();
canvas.drawLine(r.left, canvas.getHeight()/2,r.right,canvas.getHeight()/2, mBasePaint);
}
现在,这个drawable用于layer-list
参数color
和width
,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<cdev.mypreferences.SeekBarBackgroundDrawable
android:width="1dp" android:color="@color/bg_color">
</cdev.mypreferences.SeekBarBackgroundDrawable>
</item>
<item android:id="@android:id/progress">
<clip>
<shape android:shape="rectangle">
<corners android:radius="20dp"></corners>
<solid android:color="@color/seekbar_progress"></solid>
</shape>
</clip>
</item>
</layer-list>
如何从xml
到Drawable
课程中获取参数?我需要设置mBasePaint
笔画宽度和颜色?
答案 0 :(得分:1)
Declaring custom drawables in xml
可以从API 24开始实现,但我无法使用文档中提到的第一种方法成功实现这一点。
然而,由于问题与其他方面有关,我将尝试回答这一部分。
在自定义Drawable
类中添加此项将返回您感兴趣的值:
private final int[] attrsArray = new int[] {
android.R.attr.width,
android.R.attr.color,
};
@Override public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser,
@NonNull AttributeSet attrs) throws XmlPullParserException, IOException {
super.inflate(r, parser, attrs);
final TypedArray a = r.obtainAttributes(attrs, attrsArray);
float width = a.getDimensionPixelSize(0, 0);
@SuppressLint("ResourceType")
int color = a.getColor(1, 0);
a.recycle();
}