我通过编程方式将自定义视图添加到垂直线性布局中,我希望在视图之间有一些空间。我已经尝试添加: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);

当前回答

如果你使用ActionBarSherlock,你可以使用com.actionbarsherlock.internal.widget.IcsLinearLayout:

<com.actionbarsherlock.internal.widget.IcsLinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="@drawable/list_view_divider"
        android:dividerPadding="2dp"
        android:showDividers="middle" >
...
</com.actionbarsherlock.internal.widget.IcsLinearLayout>

其他回答

从API Level 14开始,你可以添加一个(透明的)分隔符绘制:

android:divider="@drawable/divider"
android:showDividers="middle"

它会帮你处理剩下的!

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

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>

Android现在支持在视图之间添加一个Space视图。它可以从4.0 ICS开始使用。

下面的示例仅以编程方式完成所需的工作。我使用的固定大小为(140,398)。

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

尝试添加空间小部件后,添加视图如下:

layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)