How to make space between LinearLayout children?

I am programatically adding custom views to a vertical LinearLayout, and I would like there to be some space between the views. I have tried adding: setPadding(0, 1, 0, 1) to my CustomView constructor, but this doesn't seem to have any effect. Any advice?

*It was pointed out that I should use margins. Since I am dynamically adding views, I need to set the margins from code (not in xml). I believe the way to do this is below, but it isn't working.

public class MyView extends View
{
    public MyView (Context context)
    {
        super(context);

        MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT,  LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 10, 0, 10);
        setLayoutParams(params);

*Edit. I also tried using MarginLayoutParams as a parameter while adding the views to the Linear layout (as below). This also did not work:

MarginLayoutParams params = new MarginLayoutParams(linearLayout.getLayoutParams());
linearLayout.setMargins(0, 10, 0, 10);
linearLayout.addView(view, params);

Solution 1:

The API >= 11 solution:

You can integrate the padding into divider. In case you were using none, just create a tall empty drawable and set it as LinearLayout's divider:

    <LinearLayout
            android:showDividers="middle"
            android:divider="@drawable/empty_tall_divider"
...>...</LinearLayout>

empty_tall_divider.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
            android:height="40dp"
            android:width="0dp"/>
</shape>

Solution 2:

You should android:layout_margin<Side> on the children. Padding is internal.

Solution 3:

Android now supports adding a Space view between views. It's available from 4.0 ICS onwards.

Solution 4:

The sample below just does what you need programatically. I have used a fixed size of (140,398).

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(140, 398);
        layoutParams.setMargins(24, 0, 24, 0);
        layout.addView(button,layoutParams);