如何为列表视图添加边距 header?

How to add margin to listview header?

我正在尝试将 textview 添加到 listview header 并为其留出左边距。这是我所做的:

//create a textview, not inflating from layout
TextView selectAdressText = new TextView(getContext());
selectAdressText.setTextSize(12);
selectAdressText.setTextColor(getResources().getColor(R.color.text_black));

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 0, 10, 10);
selectAdressText.setLayoutParams(lp);   

addressesLV.addHeaderView(selectAdressText);

但它给出了 nullpointerexception。我还尝试了 AbsListViewLayout params 而不是 LinearLayoutLayoutParams 但它没有 setMargins 方法。那么我应该使用哪个 LayoutParams 呢?

谢谢

LinearLayout header = new LinearLayout(this);
LinearLayout.LayoutParams lp = new  LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 0, 10, 10);
TextView t = new TextView(this);
header.addView(t,lp);
addressesLV.addHeaderView(header);
try it.

只需在 xml

中创建您的 textView
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="0dp"/>



View view = inflater.inflate(R.layout.textView, yourListview, false);
yourListview.addHeaderView(view);

边距被 ListView 覆盖,因此您不能直接在 xml 布局的根视图上使用边距。请改用填充。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingRight="10dp"
    android:paddingLeft="0dp"/>

或围绕它包裹一个布局(作为根节点):

<Framelayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">


   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:layout_marginBottom="10dp"
      android:layout_marginRight="10dp"
      android:layout_marginLeft="0dp"/>

</Framelayout>