使用 LinearLayout 的自定义小部件未获得 onDraw()

发布于 2024-09-14 15:14:50 字数 973 浏览 9 评论 0原文

我正在通过扩展 LinearLayout 创建自定义小部件:

public class MyWidget extends LinearLayout {
    private static Paint PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
    static {
        PAINT.setColor(Color.RED);
    }

    public MyWidget(Context context) {
        this(context, null);
    }

    public MyWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight()/2, canvas.getWidth()/2, PAINT);
        // never gets called :-(
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        // this gets called, but with a canvas sized after the padding.
    }
}

我可以很好地添加子项,但我的自定义 onDraw() 永远不会被调用。 dispatchDraw() 被调用,但似乎有不同的画布(位于填充内的画布。我需要在整个布局区域上绘制)。是否需要设置一些标志才能为布局调用 onDraw()

I'm creating a custom widget by extending LinearLayout:

public class MyWidget extends LinearLayout {
    private static Paint PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
    static {
        PAINT.setColor(Color.RED);
    }

    public MyWidget(Context context) {
        this(context, null);
    }

    public MyWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight()/2, canvas.getWidth()/2, PAINT);
        // never gets called :-(
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        // this gets called, but with a canvas sized after the padding.
    }
}

I can add children just fine, but I'm never getting my custom onDraw() being called. dispatchDraw() gets called, but that seems to have a different canvas (the one that's within the padding. I need to draw on the whole layout area). Is there some flag that needs to get set to get onDraw() called for the layout?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭了丶谁疼 2024-09-21 15:14:50

您需要在构造函数中调用setWillNotDraw(false)

因为默认情况下布局不需要绘制,所以一个优化是不调用 is draw 方法。通过调用 setWillNotDraw(false),您可以告诉 UI 工具包您想要绘制。

You need to call setWillNotDraw(false) in your constructor.

Because by default a layout does not need to draw, so an optimization is to not call is draw method. By calling setWillNotDraw(false) you tell the UI toolkit that you want to draw.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文