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

当前回答

使用LinearLayout。LayoutParams代替MarginLayoutParams。这是文档。

其他回答

如果你使用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>

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

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:layout_margin<Side>。填充是内部的。

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

是这样的:

使用LinearLayout。LayoutParams代替MarginLayoutParams。这是文档。