如何为listview标题添加保证金?

时间:2015-04-27 08:42:43

标签: android listview nullpointerexception layoutparams

我正在尝试添加textviewlistview标题,并为其添加左边距。这是我做的:

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

由于

3 个答案:

答案 0 :(得分:6)

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.

答案 1 :(得分:1)

保证金被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>

答案 2 :(得分:0)

只需在xml中创建textView

int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
    if (total[index] < 500) {
         totalLowNumber[lowIndex++] = total[index];
    } else {
         totalLargeNumber[largeIndex++] = total[index];
}