listview黏性标题

来源:互联网 发布:软件蓝图设计 编辑:程序博客网 时间:2024/06/14 20:06

对于黏性标题我把它归为两类,1:一个标题不动的,也就是今天这篇文章。2:多个标题的,也就是标题内容是根据类别变化的,类似于汽车类,水果类,蔬菜类。第二种情况 我后期文章再写,今天先写一个标题不变化的。

思路:根据listview滑动的item判断标题是否显示,listview设置setOnScrollListener方法,也就是监听listview,如果firstVisibleItem(屏幕内顶层的Item)是你想要显示悬浮标题的情况时,就显示悬浮布局。本文是:当第一个标题是firstVisibleItem时,标题就悬浮显示。

先附上效果图:
这里写图片描述

然后是滑动之后:“name0”永远在第一个
这里写图片描述

首先是XML布局:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_sticky_listview"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.mytest.StickyListview.StickyListview">    <ListView        android:id="@+id/listview"        android:layout_width="match_parent"        android:layout_height="match_parent"></ListView>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="#ffffff">        <TextView            android:id="@+id/text_sticky"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="name0"/>    </LinearLayout></RelativeLayout>

然后是head的XML:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/image_head"        android:layout_width="match_parent"        android:layout_height="100dp"        android:text="头部标题"        android:background="#ffffff"/></LinearLayout>

然后是核心代码:

listView.setOnScrollListener(new AbsListView.OnScrollListener() {            @Override            public void onScrollStateChanged(AbsListView view, int scrollState) {            }            @Override            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {                if(firstVisibleItem >= 1){                    text_sticky.setVisibility(View.VISIBLE);                }else{                    text_sticky.setVisibility(View.GONE);                }            }        });

text_sticky也就是悬浮标题,当head不显示时,也就是firstVisibleItem是第一个item(第零个是head),此时text_sticky显示。反之text_sticky不显示。

至此大功告成!简单吧?!

1 0