如果以编程方式添加视图,则忽略layout_weight

时间:2018-08-21 15:22:57

标签: android-linearlayout

我有一个视图,其中有两个项目在水平方向上对齐,彼此相邻,占据了父级的整个宽度(50:50):

char str[] = "Hello World";

printf("%s\n", reverse(str));

它按预期工作:

enter image description here

问题是,当我尝试以编程方式将这些项(item.xml)添加到父项(container.xml)时,由于某种原因,layout_weight属性似乎被忽略了。而不是将项目填充/扩展为全宽,每个项目占用几个像素的空间:

enter image description here

我通过以下方式以编程方式添加视图:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/selection_container">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#0c2003">
    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#Ac2003">
    </LinearLayout>

</LinearLayout>

我后来尝试致电:

LinearLayout container = mainView.findViewById( R.id.container );
View item1 = LayoutInflater.from( mainView.getContext() ).inflate( R.layout.item, null, false );
View item2 = LayoutInflater.from( mainView.getContext() ).inflate( R.layout.item, null, false );
container.addView( item1 );
container.addView( item2 );

但这没什么区别。

container.xml:

container.invalidate();
container.requestLayout();

item.xml:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/selection_container"/>

以编程方式添加视图时,为什么会忽略layout_weight属性?谢谢!

1 个答案:

答案 0 :(得分:0)

问题是我没有为inflate函数提供'parent'参数。如果未提供该参数,则将忽略诸如width / height / weight之类的某些属性,因为充气机需要知道其父级是谁,以便正确布置充气后的视图。

View item1 = LayoutInflater.from( mainView.getContext() ).inflate( R.layout.item, (ViewGroup)itemView, false );
相关问题