在View的onDraw方法中,Android getWidth()返回0

4

这是我的代码:

    if (myView == null) {
        myView = new View(mContext) {
            @Override
            protected void onDraw(final Canvas canvas) {
                super.onDraw(canvas);
                final float width = (float)getWidth();
                ......
            }
        };

        addView(myView);
    }

    requestLayout();

尽管mContext的大小不为零,但我的代码中的宽度始终为0。有人能给出可能导致宽度为0的原因吗?谢谢。


请展示布局XML。 - programmer23
请查看此链接 - https://dev59.com/8XI95IYBdhLWcg3wyA-c - Mel
我认为问题在于我的父视图没有显示出来。 - Bagusflyer
2个回答

3

您需要在 onSizeChanged 处理程序中记录画布的尺寸,然后在 onDraw 处理程序中使用它们。

private int canvasWidth;
private int canvasHeight;

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    canvasWidth = w;
    canvasHeight = h;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    final float width = (float)canvasWidth;
    ...
}

谢谢,我会尝试的。 - Bagusflyer
我接受你的答案并不是因为它解决了我的问题,而是因为我欣赏你的建议。谢谢。 - Bagusflyer

-1
作为一名新手,我认为你的新视图是空白的,所以它的宽度和高度都是0。 也许你应该尝试设置它的布局参数,给定一些硬编码的高度和宽度。
目前onmeasure没有任何东西可以测量。 可能吧。 :P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接