【问题标题】:android : set margin between buttons with LayoutParamsandroid:使用 LayoutParams 设置按钮之间的边距
【发布时间】:2012-10-16 11:58:07
【问题描述】:

我想垂直自动生成按钮,按钮之间的底部边距为 20 像素。我尝试使用 LayoutParams 对象设置边距,但没有成功。

<?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);

        }

正如您在图片上看到的,图片之间没有空格。有人知道为什么吗? 谢谢 !

【问题讨论】:

  • 你为什么使用 FrameLayout ? XML 文件位于 LinearLayout 中。

标签: android button layoutparams


【解决方案1】:

你可以试试这个:

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) button.getLayoutParams();
layoutParams.bottomMargin += 20;
button.setLayoutParams(layoutParams);

【讨论】:

【解决方案2】:

尝试使用LinearLayout.LayoutParams 而不是FrameLayout.LayoutParams,因为在您的xml 中您使用的是LinearLayout..

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

【讨论】:

  • Cata 比你快,抱歉。感谢您的帮助