getWidth and getHeight are returning a zero

后端 未结 6 1449
一整个雨季
一整个雨季 2020-12-03 07:12

I am trying to make a simple drawing program for the android.

I have a custom View class to handle the drawing. When I call its getWidth an

相关标签:
6条回答
  • 2020-12-03 07:45

    Just Use the getViewTreeObserver() Listener, and inside this just calculate the height and width.

    Follow the code :

    getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //Do your Stuff calculation , like view.getWidth() ... });

    0 讨论(0)
  • 2020-12-03 07:45

    The view only has dimensions after beeing displayed for the first time.

    Other thing:

    int h=getHeight();
    h=400;
    

    Is useless no ? Is it just for testing ?

    0 讨论(0)
  • 2020-12-03 07:53

    Complementing Mah's answer, I found out that you can get the values from parameters, like the code bellow:

    ImageView imageProcess = (ImageView) li.inflate(
        R.layout.andamento_sinistro_imageprocess, centerLayout, false);
    imageProcess.setBackgroundResource(
        (isActive)?(R.drawable.shape_processon):(R.drawable.shape_processoff));
    RelativeLayout.LayoutParams imageProcessParams = 
        (RelativeLayout.LayoutParams)imageProcess.getLayoutParams();
    imageProcessParams.leftMargin = 
        (int) (centerPosition - 0.5*imageProcessParams.width);
    imageProcessParams.addRule(RelativeLayout.CENTER_VERTICAL);
    centerLayout.addView(imageProcess);
    

    The real catch here is the use of the LayoutParams, that have rules yet not processed by the element.

    0 讨论(0)
  • 2020-12-03 07:54

    You should call getWidth() and getHeight() in the overrided method onLayout.

    0 讨论(0)
  • 2020-12-03 08:11

    I'm not certain, but it may have something to do with where the code is in the lifecycle of your activity. If you're calling getWidth() and getHeight() before the View is displayed on screen, you'll get a value of 0. I've had that happen to me, too.

    I'm not sure if there's a way around this. I had to rely on getting the hardware screen's width and height, instead of the view's width and height. You might end up having to approximate the width and height of your view and hard coding it.

    0 讨论(0)
  • 2020-12-03 08:12

    The width and height are not defined until the view is actually rendered to the screen.

    Use protected abstract void onLayout (boolean changed, int l, int t, int r, int b) (which you override in your activity) to know when the sizes are ready.

    0 讨论(0)
提交回复
热议问题