【问题标题】:How to add margin to listview header?如何为列表视图标题添加边距?
【发布时间】:2015-07-05 15:00:31
【问题描述】:

我正在尝试将 textview 添加到 listview 标头并为其留出左边距。这是我的工作:

//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 参数而不是LinearLayoutLayoutParams,但它没有setMargins 方法。那么我应该使用哪个LayoutParams 呢?

谢谢

【问题讨论】:

  • 先addHeaderView,然后设置AbsListView.LayoutParams。

标签: android listview nullpointerexception layoutparams


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    只需在 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);
    

    【讨论】:

      【解决方案3】:
      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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-29
        • 2020-01-05
        • 1970-01-01
        • 1970-01-01
        • 2022-09-30
        • 2015-08-21
        • 2015-10-09
        • 1970-01-01
        相关资源
        最近更新 更多