5

I want to automatically generate buttons vertically with a bottom margin of 20px between buttons. I try to set margin with a LayoutParams object, without success.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/regions_search"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginBottom="30dip"
    android:orientation="vertical" >
</LinearLayout>



@Override
public void onCreate(Bundle savedInstanceState) {

    ...

    for (Region region : regionsList) {

        //create new button     
        Button button = new Button(mContext);

        //set infos
        int id = Integer.parseInt(Long.toString((Long) region.getId()));        button.setId(id);
        button.setText(region.getName() + "( " + region.getStores_nb() + " )");

        //Layoutparams setting
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 20);

        button.setLayoutParams(params);

        myLinear.addView(button);

        }

As you can see on image, there is no space between images. Someone knows why ? Thank you ! enter image description here

johann
  • 1,115
  • 8
  • 34
  • 60

2 Answers2

10

You can try this:

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) button.getLayoutParams();
layoutParams.bottomMargin += 20;
button.setLayoutParams(layoutParams);
Cata
  • 11,133
  • 11
  • 65
  • 86
  • Thank you ! All of you give me the same answer, but you were the first to post ! Thank you ~ – johann Oct 26 '12 at 08:48
  • please watch this http://stackoverflow.com/questions/16552811/set-a-margin-between-two-buttons-programmatically-from-a-linearlayout?noredirect=1#comment23779639_16552811 – Dimitri May 14 '13 at 21:42
2

Try to use LinearLayout.LayoutParams instead of FrameLayout.LayoutParams, as in your xml you are using LinearLayout..

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
Nermeen
  • 15,883
  • 5
  • 59
  • 72