安卓:使用LayoutParams设置按钮之间的间距

5
我希望能够垂直自动生成按钮,并在按钮之间设置底部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。 - Nirav Ranpara
2个回答

10

你可以尝试这个:

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

谢谢!你们所有人都给了我相同的答案,但是你是第一个发布的!谢谢~ - johann
请查看以下链接:https://dev59.com/Z2Qn5IYBdhLWcg3wzZ36?noredirect=1#comment23779639_16552811 - Dimitri

2

在xml中使用LinearLayout时,尝试使用LinearLayout.LayoutParams而不是FrameLayout.LayoutParams

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

1
Cata比你更快,抱歉。感谢你的帮助。 - johann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接