Android 从xml获取自定义可绘制参数
我的定制绘图如下:Android 从xml获取自定义可绘制参数,android,android-layout,android-custom-view,android-drawable,android-resources,Android,Android Layout,Android Custom View,Android Drawable,Android Resources,我的定制绘图如下: public class SeekBarBackgroundDrawable extends Drawable { Paint mBasePaint = null; public SeekBarBackgroundDrawable() { super(); mBasePaint = new Paint(); mBasePaint.setAntiAlias(true); mBasePaint.s
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);
}
现在,该可绘制图形在图层列表中使用,参数颜色和宽度如下:
<?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笔划宽度和颜色?可以从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();
}