我通过编程方式将自定义视图添加到垂直线性布局中,我希望在视图之间有一些空间。我已经尝试添加:setPadding(0,1,0,1)到我的CustomView构造函数,但这似乎没有任何影响。任何建议吗?

有人指出我应该使用边距。因为我是动态添加视图,所以我需要从代码中设置边距(不是xml格式)。我相信这样做的方法是下面,但这是行不通的。

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

*编辑。我还尝试使用MarginLayoutParams作为参数,同时将视图添加到线性布局(如下所示)。这也没有起作用:

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

当前回答

你应该在子节点上android:layout_margin<Side>。填充是内部的。

其他回答

你可以得到父LinearLayout的LayoutParams,并应用到各个视图:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(8,8,8,8);

注意setedges()将像素作为int数据类型。所以,在加值之前转换为dp 上面的代码将把高度和宽度设置为wrap_content。你可以自定义它。

API >= 11解:

你可以把填充物整合成分隔线。如果你没有使用,只需要创建一个高空的可绘制对象,并将其设置为LinearLayout的分隔符:

    <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>

你只需要用layout_weight的线性布局来包装项目。要将项目水平分开,请使用此选项

<LinearLayout
    ...
    ...
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center">

      // your item

  </LinearLayout>
</LinearLayout>

你可以使用android:layout_weight="1"

是这样的:

在子视图的布局中使用填充。

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_margin="5dp"
          android:background="@drawable/backage_text"
          android:textColor="#999999"
           >

</TextView>

backage_text.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/white"/>
    <corners android:radius="2dp"/>
    <stroke
        android:width="1dp"
        android:color="#999999"/>
    <padding
        android:bottom="5dp"
        android:left="10dp"
        android:right="10dp"
        android:top="5dp" />
</shape>