获取设置为包装内容的布局高度

cod*_*oid 3 android android-linearlayout

我想获得设置为包装内容的线性布局的高度。但它是零。我试试这个代码:

 final LinearLayout below= (LinearLayout) findViewById(R.id.below);


         ViewTreeObserver vto = below.getViewTreeObserver();  
         vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  
             @Override  
             public void onGlobalLayout() {  
                  width  = below.getMeasuredWidth(); 
                  height = below.getMeasuredHeight();  

             }  
         });
Run Code Online (Sandbox Code Playgroud)

和 :

 LinearLayout below= (LinearLayout) findViewById(R.id.below);
       final int belowh=below.getHeight();
Run Code Online (Sandbox Code Playgroud)

使用代码:

 final LinearLayout below= (LinearLayout) findViewById(R.id.below);
        ViewTreeObserver vto = below.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @Override 
            public void onGlobalLayout() { 

        if(below.getMeasuredHeight()> 0){

                 this.below.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
                int width  = below.getMeasuredWidth();
                int height = below.getMeasuredHeight(); 
        }
            } 
        })

    ;
Run Code Online (Sandbox Code Playgroud)

点击这里查看

Pha*_*inh 5

在创建视图后尝试使用此代码获取布局宽度和高度

final LinearLayout below= (LinearLayout) findViewById(R.id.below);
    below.post(new Runnable() 
        {
            @Override
            public void run()
            {
                Log.i("TAG", "Layout width :"+ below.getWidth());
                Log.i("TAG", "Layout height :"+ below.getHeight());
            }
    });
Run Code Online (Sandbox Code Playgroud)

希望这有帮助