爲ListView增長Header (可動態修改其中的內容) java
1.新建一個Layout:
demo_list_item_header_view.xml android
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 this
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以前
加上代碼: spa
Java代碼
- DemoListHeaderView headerView = new DemoListHeaderView(context);
- headerView.setTextView("Header : ");
- listView.addHeaderView(headerView);