自定义视图未在预览中显示

时间:2016-12-05 07:37:18

标签: android android-custom-view

我构建了一个非常简单的自定义视图,只绘制一条线。

当我运行代码时视图正常工作,但我在预览窗口中看不到任何内容。

我找到了解决方案,比如使用Relative layout / ViewGroup等,但我只想扩展View类(只是因为我想知道并学习如何正确完成)。

customView.java

public class customView extends View {
    float lineWidth = 5;
    Paint linePaint;

    public void setLineWidth(float width) {
        lineWidth = width;
    }

    public float getLineWidth() {
        return lineWidth;
    }

    public customView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttributes(context, attrs);
        initPaints();
    }

    private void initAttributes(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.customView, 0, 0);
        try {
            setLineWidth(typedArray.getDimension(R.styleable.customView_cv_line_width, getLineWidth()));
        }
        finally {
            typedArray.recycle();
        }
    }

    private void initPaints() {
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setColor(Color.BLUE);
        linePaint.setStrokeWidth(lineWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float midHeight = canvas.getHeight() / 2;
        canvas.drawLine(0, midHeight, canvas.getWidth(), midHeight, linePaint);
    }

    /*// try to operate onMeasure, not helps
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(200, 100);
    }*/
}

attrs.xml

<resources>
    <declare-styleable name="customView">
        <attr name="cv_line_width" format="dimension" />
    </declare-styleable>
</resources>

我很高兴知道为什么我在xml预览上看到一个空矩形以及如何修复它,谢谢!

0 个答案:

没有答案