I'm creating dynamically views containing a LinearLayout
and add them to an outer LinearLayout
. I would like to set a margin around the created views, but the layout_margin
in the XML file is ignored. It works, if I set the parameters in the code, but I would like to specify the margin in the layout XML.
Setting the margin in the XML layout will be ignored:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical" >
...
</LinearLayout>
Setting the margin while creating is honored:
LinearLayout productView = (LinearLayout) getLayoutInflater().inflate(R.layout.product_preview, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50, 50, 50, 50);
productView.setLayoutParams(params);
This is the outer layout. The views are added to dealer_activity_product_list
.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/dealer_activity_dealer_image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="@string/dealer_activity_dealer_image_desc" />
<TextView
android:id="@+id/dealer_activity_dealer_address"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/dealer_activity_product_list1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/dealer_activity_product_list2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" />
</LinearLayout>
</LinearLayout>
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify the layout direction with the android:orientation attribute. Note: For better performance and tooling support, you should instead build your layout with ConstraintLayout.
3. android:layout_marginTop: It specifies the extra space on the top side of the view.
Are you setting the attribute for the inner LinearLayout or the containing LinearLayout? At least, the following does work inside a LinearLayout:
<TextView
android:id="@+id/xxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="10dp"
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With