Reputation: 773
I have a View, in which I have two items aligned horizontally next to teach other, taking up the whole width of the parent (50:50):
<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>
It works as expected:
The problem is when I try to add these items (item.xml) to the parent (container.xml) programmatically, the layout_weight property seems to be ignored for some reason. Instead of items filling/expanding to full width, each item takes up few pixels of space:
I'm adding the views programmatically the following way:
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 );
I tried to call afterwards:
container.invalidate();
container.requestLayout();
but that didn't make any difference.
container.xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/selection_container"/>
item.xml:
<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>
Why are the layout_weight properties are ignored, when adding the view programmatically? Thanks!
Upvotes: 1
Views: 155
Reputation: 773
The problem was that I did not provide the 'parent' argument for the inflate function. If the argument is not provided some attributes like the width/height/weight are ignored as the inflator needs to know who its parent is in order to lay out the inflated view properly.
View item1 = LayoutInflater.from( mainView.getContext() ).inflate( R.layout.item, (ViewGroup)itemView, false );
Upvotes: 2