Android 为什么线性布局';s码-1码?

Android 为什么线性布局';s码-1码?,android,android-layout,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" an

我想知道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>

您获得
-1
的原因是
宽度
参数设置为
匹配父项
,该参数的值为
-1

要获得布局的大小,应该使用
getWidth()
getMeasuredWidth()
方法。然而,在对视图进行测量之前,这些方法不会给出有意义的答案。在这里阅读

通过将
onWindowFocusChanged()
as重写,可以获得正确的大小

或者,(黑客解决方案),您可以这样做:

@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());
        }
    });
}

“黑客解决方案”之所以是黑客解决方案,是因为…?它主要起作用,但我不确定框架是否提供了任何保证,即在测量布局之后,
post
。。也许在未来的版本中。。他们调整了测量和布局机制,我们可能会发现
post
以前发生过。。我不认为这是官方记录的。这很可能是因为你应该发布视图的父视图,而不是视图本身,因为父视图布置了它的子视图。也就是说,子视图可能无法准确地知道它是否实际完成了布局,但父视图应该这样做。在中有一个这样的例子。是的。。这是一个很好的观察。谢谢你指出这一点。。请记住:)
public static final int MATCH_PARENT = -1;
@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());
        }
    });
}