为什么linearlayout的大小为-1?

时间:2013-11-25 01:45:54

标签: android android-layout

我正在尝试获得linearlayout的大小。

我测试了以下代码。

但我得到的值是-1(linearlayout的宽度)。

如何获得正确的尺寸?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/mainLayout"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MyActivity"
            />
</LinearLayout>


package com.example.LayoutSize;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainLayout);
        ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams();

        System.out.printf("linearLayout width : %d", layoutParams.width);

    }
}

2 个答案:

答案 0 :(得分:1)

获得-1的原因是因为width参数设置为MatchParent,其值为-1

要获得布局的大小,您应该使用getWidth()getMeasuredWidth()方法。但是,在测量视图之前,这些方法不会给您有意义的答案。在这里阅读how android draws views

您可以将onWindowFocusChanged()改为mentioned in this thread来获得正确的尺寸。

或者,( hacky solution ),您可以这样做:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainLayout);
    linearLayout.post(new Runnable() {
        @Override
        public void run() {
            System.out.printf("linearLayout width : %d", linearLayout.getMeasuredWidth());
        }
    });
}

答案 1 :(得分:0)

public static final int MATCH_PARENT = -1;