如何为自定义imageview的属性设置值?

时间:2019-05-09 11:15:32

标签: java android custom-view

我有一个自定义的Imageview类,如下所示。我有一个名为timeInterval的字段,该字段在构造函数中传递,但在onDraw中它的值为0。传递此值的正确方法是什么?我也不知道是否可以动态传递它作为属性。

public class ProgressBarView extends AppCompatImageView {

    private final Handler mHandler = new Handler();
    private int mTimeInterval;
    private int mColor;
    private int[] mLocations = new int[2];

    public ProgressBarView(Context context, int timeInterval) {
        super(context);
        mTimeInterval = timeInterval;
        init(null);
    }

    public ProgressBarView(Context context, AttributeSet attrst) {
        super(context, attrst);
        init(attrst);
    }

    public ProgressBarView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ProgressBarView);
        mColor = typedArray.getColor(R.styleable.ProgressBarView_overlay_color, Color.BLACK);
    }

    public void updatePainting() {
        mHandler.postDelayed(this::invalidate, mTimeInterval / 360);
    }

    @Override
    public void onDraw(final Canvas canvas) {
        if (mTimeInterval == 0) {
            return;
        }
        Calendar now = Calendar.getInstance();
        int seconds = now.get(Calendar.SECOND);
        int mStartAngel = (int) (((float) (seconds % (mTimeInterval / 1000))
                / (mTimeInterval / 1000)) * 360);
        final Paint paint = new Paint(Paint.DITHER_FLAG);
        paint.setColor(mColor);
        paint.setStyle(Paint.Style.FILL);
        paint.setAlpha(-50);
        getLocationOnScreen(mLocations);
        int radius = getWidth() / 2;
        float centreX = this.getX() + radius;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawArc(centreX - radius, centreX - radius, centreX + radius, centreX + radius, 0, mStartAngel, true, paint);
        } else {
            final RectF oval = new RectF();
            oval.set(centreX - radius, centreX - radius, centreX + radius, centreX + radius);
            canvas.drawArc(oval, 0, mStartAngel, true, paint);
        }
        updatePainting();
    }
}

我这样实例化它:

mProgressBarView = new ProgressBarView(getContext(), timeInterval);

1 个答案:

答案 0 :(得分:0)

您忘记了“这个”

public ProgressBarView(Context context, int timeInterval) {
    super(context);
    this.mTimeInterval = timeInterval;
    init(null);
}