Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getWidth() and getHeight() for custom view give wrong values [duplicate]

I've got a Custom View where I draw a grid onto a canvas. I want the grid to be drawn so that the outer edges of the grid coincide with the edges of the device screen. I use the getWidth() and getHeight() methods to determine the dimensions of my grid and then draw it, but the grid that appears always has cells drawn off-screen.

If I get the width and height of the display and use those for drawing instead then the width of my grid will be what I want, but the height is still off because some the height of the display is taken up by battery and wifi indicators, etc. Also, I don't want to use these values as I want to be able to embed my view in larger xml layouts.

Below is the code where I find my view width and height in my custom 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);
}

and the onDraw of my custom view:

@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);
    }
}       

}

The approach I've followed is similar to this but has not worked. How can I get the true values for the width and height of my view? Thanks for reading!

like image 241
Rookatu Avatar asked Feb 16 '26 22:02

Rookatu


1 Answers

I'm guessing you have already seen this?

Custom View Height and Width

Or perhaps this is a different problem.

like image 181
James Manes Avatar answered Feb 19 '26 11:02

James Manes