Search code examples
javaandroidreturnrunnablemeasurement

getHeight and getMeasuredHeight return 0, even in Runnable


So i was searching threw all the getHeight/widht problems-posts, and tried the different methods to solve the problem(like the globalLayoutListener, or Runnable) , to wait, till the FrameLayout has been created... but still my getHeight returns 0. So this is my code right now:

private void zurechtruecken() {
    int n=1;

    spB =(FrameLayout) findViewById(R.id.spielbereich);

    spB.post(new Runnable(){
        @Override
        public void run(){

            spielBh=spB.getMeasuredHeight();
            spielBb=spB.getMeasuredWidth();
        }
    });

This was my code with the GlobalLayoutListener:

private void zurechtruecken() {
    int i=24;
    int n=1;

    mView = findViewById(R.id.spielbereich);
    mView.getViewTreeObserver().addOnGlobalLayoutListener( 
        new OnGlobalLayoutListener(){

            @Override
            public void onGlobalLayout() {
                mView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                spielBh=mView.getHeight();
                spielBb=mView.getWidth();
                Log.i("!",Integer.toString(spielBh));
                Log.i("!",Integer.toString(spielBb));


            }
        });

the "removeGlobalLayoutListener(this)" was crossed.(it was deprecated)

It could be important, that im measuring a Frame Layout


Thanks for any help!! Botti560


Solution

  • I too have had troubles like this before. If all else fails, extend FrameLayout in your own class and get the height/width values in the onMeasure method. Example:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        int height = MeasureSpec.getSize(heightMeasureSpec);
    
    }
    

    Easy to put it in you XML layout too with something like:

    <com.yourdomain.yourappname.FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" > ...