Android Listview固定列头
背景
之前Listview列是通过把列名作为第一行的数据实现的,当Listview数据行超过一定高度时会出现滚动条,当滚动条向下滚动时作为列头的第一行就会向上滚动,最后看不见 ,影响用户体验,如何在向下滚动时固定列表不动呢?
在网上查阅相关资料有的通过监听滚动距离来实现,综合各种信息最后采用了单独控件做列头的方案,该方案不使用任何第三方控件,简单容易理解,独立于Listview,无论Listview向下滚动单独控件列头都不会跟着滚动,达到了固定列头的效果。
主要思路是title列和Listview行共享一个布局文件,只有共享同一个布局文件才能保证列头和行对齐,然后用HorizontalScrollView包裹起来,Listview渲染数据时,可以自定义行的style,以跟title样式区分。因为HorizontalScrollView只能包含一个控件,所以要先通过ConstraintLayout先将title列和Listview包裹起来,这里用HorizontalScrollView的目的是ListView列多的情况下通过左右滚动条可以浏览全部列的数据。

实现步骤:
1、activity布局文件 activity_barcode_check_doc_list_form.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".forms.warehouse.BarcodeCheckDocListForm">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="280dp"
android:id="@+id/horizontalScrollView"
tools:layout_constraintTop_creator="1"
tools:layout_constraintBottom_creator="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="0dp"
app:layout_constraintTop_toBottomOf="@+id/lblDocAmount"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="20dp"
app:layout_constraintLeft_toLeftOf="parent"
>
<android.support.constraint.ConstraintLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!---固定列-->
<include android:id="@+id/listview_title"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
layout="@layout/barcode_check_doc_list">
</include>
<ListView
android:id="@+id/listView_Barcode"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/listview_title"
android:layout_marginTop="40dp"
android:choiceMode="singleChoice"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1" />
</android.support.constraint.ConstraintLayout>
</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>
2、title列和Listview行的布局文件 barcode_check_doc_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/text_doc_no"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:paddingBottom="10dip"
android:paddingTop="10dip"
android:singleLine="true"
android:text="订单"
android:textColor="#ffffff"
android:background="@color/colorPrimary"
android:textSize="15sp" />
<View
android:layout_width="1.5dip"
android:layout_height</