自定义视图不绘制自身

wha*_*ide 5 android android-custom-view android-layout

我在这里阅读了有关此主题的不同问题,但我仍然找不到答案。出于任何原因,请随时关闭此问题。

我有一个简单的Circle类扩展View.

这个类的代码是:

public class ProgressCircle extends View {
    Paint mCirclePaint;
    float extRadius;
    float viewWidth, viewHeight;
    float centerX, centerY;

    public ProgressCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        init();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        float xpad = (float) getPaddingLeft() + getPaddingRight();
        float ypad = (float) getPaddingTop() + getPaddingBottom();
        float ww = (float)w - xpad; float hh = (float)h - ypad;
        extRadius = Math.min(ww, hh) / 2;

        viewWidth = this.getWidth();
        viewHeight = this.getHeight();
        centerX = viewWidth / 2; centerY = viewHeight / 2;

        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(centerX, centerY, extRadius, mCirclePaint);
        canvas.drawText("ciao", 0, 0, mCirclePaint);    
    }

    private void init() {
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(0x666666);
        mCirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }
Run Code Online (Sandbox Code Playgroud)

我确认在创建主要活动时(通过使用 some Log.d()s)会调用该类中的每个方法。我<com.mypackage.Circle>在我的主要活动中添加了一个元素,LinearLayout然后我添加了一个示例测试按钮。

我实现的是按钮显示而我Circle的不是,但按钮(在LinearLayout之后Circle)仍然不是布局的第一个元素:这让我认为确实发生了某些事情,但没有绘制任何内容。

wha*_*ide 3

这只是一个愚蠢的问题:输入的颜色mCirclePaint.setColor(0x666666)无效。它可以与文件夹mCirclePaint.setColor(Color.RED)中定义的任何其他颜色一起使用res

如果您需要指定颜色值,则必须包含透明度字节(否则您指定的不是 32 位整数,而是 24 位)。所以 0x666666 是无效的,但 0xff666666 是有效的颜色并且会绘制。