java - 自定义 View 的 getWidth() 和 getHeight() 给出了错误的值

标签 java android android-custom-view

<分区>

我有一个自定义 View ,我在 Canvas 上绘制了一个网格。我想要绘制网格,以便网格的外边缘与设备屏幕的边缘重合。我使用 getWidth()getHeight() 方法来确定我的网格的尺寸然后绘制它,但出现的网格总是在屏幕外绘制单元格。

如果我得到显示器的宽度和高度并将它们用于绘图,那么我的网格宽度将是我想要的,但高度仍然关闭,因为显示器的一些高度被电池占用并且wifi 指示器等。此外,我不想使用这些值,因为我希望能够将我的 View 嵌入到更大的 xml 布局中。

下面是我在自定义 View 中找到 View 宽度和高度的代码:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
    cellWidth = w/nCols;
    cellHeight = h/nRows;
    //find view dimensions
    viewWidth = getWidth();     //this is just equal to w
    viewHeight = getHeight();   //this is just equal to h
    super.onSizeChanged(w,h,oldw,oldh);
}

和我的自定义 View 的 onDraw:

@Override 
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);

    canvas.drawRect(0,0,viewWidth,viewHeight, background);    

    for(int i=0; i <= nRows; i++){
        canvas.drawLine(0,i*cellHeight, nCols*cellWidth,i*cellHeight,lines);
        canvas.drawLine(i*cellWidth, 0, i*cellWidth, nRows*cellHeight, lines);
    }
}       

我采用的方法类似于 this但没有奏效。 如何获得 View 宽度和高度的真实值? 感谢阅读!

最佳答案

我猜你已经看过了?

Custom View Height and Width

或者这可能是另一个问题。

关于java - 自定义 View 的 getWidth() 和 getHeight() 给出了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969841/

相关文章:

java - 安卓上按住音量键?

java - 如何从 firebase 实时数据库中重新排序数据

android - 没有 list 。 jar 未签名。 (签名丢失或不可解析)

安卓 : Error occur on custom switch layout

安卓。 Canvas 缩放和平移

java - 是否有将 F6 作为默认加速器的 Swing 元素?

java - WinRegistry 类中的 readStringValues 方法出现 NullPointer 异常

java - java选项 -XX :+UseCondCardMark work in jdk17? 是否

android - 尝试运行简单的monkeyrunner python脚本, 'importerror no module named os'

android - 如何允许自定义 View 的 XML 属性由资源 ID 或值指定?