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

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

1.新建一个Layout:
   demo_list_item_header_view.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">  
    
    <TextView
        android:layout_height="30sp"
        android:layout_width="wrap_content"
        android:textSize="20sp" android:id="@+id/headerTextView"
        android:text="TestListViewHeader" />  

</LinearLayout>  

 

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

package com.zhang.test.view;   
  
import com.zhang.test.R;   
  
import android.content.Context;   
import android.util.AttributeSet;   
import android.view.LayoutInflater;   
import android.view.View;   
import android.widget.LinearLayout;   
import android.widget.TextView; 

public class DemoListHeaderView extends LinearLayout {   
  
    private static final String TAG = "DemoListHeaderView";   
    private Context context;   
    private TextView textView;

    public DemoListHeaderView(Context context) {   
        super(context);   
        
        this.context = context;   
        View view = LayoutInflater.from(this.context).inflate(R.layout.demo_list_item_header_view, null); 
        //以下两句的顺序不能调换,要先addView,然后才能通过findViewById找到该TextView
        addView(view);   
        textView = (TextView) view.findViewById(R.id.headerTextView);   
    }

    public void setTextView(String text) {   
        textView.setText(text);   
    }   
}  
 

 

 

 

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

DemoListHeaderView headerView = new DemoListHeaderView(context);   
headerView.setTextView("Header : ");   
listView.addHeaderView(headerView);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值