以像素为单位获取内部布局的大小

时间:2016-03-28 14:38:37

标签: android android-layout layoutparams

使用以下Java和XML代码,我想知道如何正确检索内部/子布局(LinearLayout,而父级是RelativeLayout,填充为20dp)的像素尺寸:

Java代码:

public class TestActivity extends Activity {
    private LinearLayout linLay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        linLay = (LinearLayout)findViewById(R.id.linLay);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
        linLay.setLayoutParams(lp);

        getDimensions();
    }

    private void getDimensions() {
        System.out.println(linLay.getHeight());
        System.out.println(linLay.getWidth());
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp" >

    <LinearLayout
        android:id="@+id/linLay"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true">

    </LinearLayout>
</RelativeLayout>

...因为我得到尺寸为0的输出,我知道在检索尺寸之前需要首先在屏幕上设置LinearLayout ......但是我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

在您尝试输出它时,它没有得到它的尺寸。您只需添加延迟或只使用下面的方法。

private void getDimensions() {

    ViewTreeObserver vto = linLay.getViewTreeObserver();  
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override 
        public voidonGlobalLayout() { 
            linLay.getViewTreeObserver().removeGlobalOnLayoutListener(this);      
            int height =linLay.getMeasuredHeight(); 
            int width =linLay.getMeasuredWidth();  
            System.out.println(height);
            System.out.println(width);
        }  
    });

}