android margins not working when dynamically inserting views

John Ward picture John Ward · Feb 14, 2017 · Viewed 9.5k times · Source

I have a simple view:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/contact_selected"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="5dp"
    android:orientation="horizontal"
    android:padding="3dp">
    <TextView
        android:id="@+id/txt_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Billy Bob"
        />
</LinearLayout>

When I statically copy the LinearLayout markup into my main activity layout, the margins are as expected. However, when I add the view into the main activity layout dynamically, the margins are ignored. Here's how I insert the view

LayoutInflater inflater = (LayoutInflater)
        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test, null);
TextView txt_title = (TextView)view.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #1");
llayout.addView(view, llayout.getChildCount()-1);

View view2 = inflater.inflate(R.layout.test, null);
txt_title = (TextView)view2.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #2");
llayout.addView(view2, llayout.getChildCount()-1);

Here's what it looks like:

enter image description here

The container in the main layout is a LinearLayout, which is a child of a HorizontalScrollView. Any insight is appreciated.

Answer

Submersed picture Submersed · Feb 14, 2017

When dynamically adding views, you shouldn't inflate the View with a null ViewGroup parent. So, in other words you should be using inflater.inflate(R.layout.test, linearLayout, false);. The parent is used when determining what type of layout parameters to generate. Pass your parent container (in this case, your linear layout), so it correctly instantiates the ViewGroup.MarginLayoutParams from your XML.