【问题标题】:Get custom drawable parameters from xml从 xml 获取自定义可绘制参数
【发布时间】:2017-06-09 07:55:33
【问题描述】:

我有这样的自定义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);
    }

现在,这个可绘制对象在layer-list 中使用,参数colorwidth 如下所示:

<?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笔画宽度和颜色吗?

【问题讨论】:

    标签: android android-layout android-custom-view android-drawable android-resources


    【解决方案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(); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2023-03-11
      • 2014-10-24
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多