(转)为ListView增加Header (可动态修改其中的内容)

原地址:http://que2010.iteye.com/blog/1335798


为ListView增加Header (可动态修改其中的内容)

1.新建一个Layout:
   demo_list_item_header_view.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout  
  3.     android:layout_height="wrap_content"  
  4.     android:layout_width="wrap_content"  
  5.     xmlns:android="http://schemas.android.com/apk/res/android">    
  6.       
  7.     <TextView  
  8.         android:layout_height="30sp"  
  9.         android:layout_width="wrap_content"  
  10.         android:textSize="20sp" android:id="@+id/headerTextView"  
  11.         android:text="TestListViewHeader" />    
  12.   
  13. </LinearLayout>    

 

2.然后新建一个类,继承自LinearLayout用来显示上面的Layout:
   DemoListHeaderView.java

Java代码   收藏代码
  1. package com.zhang.test.view;     
  2.     
  3. import com.zhang.test.R;     
  4.     
  5. import android.content.Context;     
  6. import android.util.AttributeSet;     
  7. import android.view.LayoutInflater;     
  8. import android.view.View;     
  9. import android.widget.LinearLayout;     
  10. import android.widget.TextView;   
  11.   
  12. public class DemoListHeaderView extends LinearLayout {     
  13.     
  14.     private static final String TAG = "DemoListHeaderView";     
  15.     private Context context;     
  16.     private TextView textView;  
  17.   
  18.     public DemoListHeaderView(Context context) {     
  19.         super(context);     
  20.           
  21.         this.context = context;     
  22.         View view = LayoutInflater.from(this.context).inflate(R.layout.demo_list_item_header_view, null);   
  23.         //以下两句的顺序不能调换,要先addView,然后才能通过findViewById找到该TextView  
  24.         addView(view);     
  25.         textView = (TextView) view.findViewById(R.id.headerTextView);     
  26.     }  
  27.   
  28.     public void setTextView(String text) {     
  29.         textView.setText(text);     
  30.     }     
  31. }    
  32.    

 

 

 

3.之后在ListView设置setAdapter之前,一定要在setAdapter之前
   加上代码:

Java代码   收藏代码
  1. DemoListHeaderView headerView = new DemoListHeaderView(context);     
  2. headerView.setTextView("Header : ");     
  3. listView.addHeaderView(headerView);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值