首先上效果图,实现如下效果:
整个主要布局就是一个ListView,主要是根据ListView可见的第一个条目是哪个条目来操作的。注意这里的“悬浮”其实只是通过 隐藏/显示 悬浮部分来实现:在ListView“背后”有一个隐藏的“悬浮部分”,当ListView条目中的悬浮部分成为ListView可见部分第一个时,这时非ListView条目中的悬浮部分显示出来,这样造成“悬浮”部分一直在顶部浮动,当ListView可见部分第一个条目并不是悬浮时,非ListView那部分“隐藏部分”继续隐藏。总之就是2个悬浮部分:ListView条目中的和处于布局顶部隐藏(Gone/invisible)的起初未显示的,通过这两部分的操作来完成整个功能的。
这里的listvie有两个头部headerview,一个是最上边标有“这里是头部内容”的头部,还有一个是标有“悬浮部分”的头部,他们都是通过listview.addheaderView()方法加入到listview中的。当没有滑动时,第一个头部的position是0,第二个头部的position是1。
看布局文件可以知道,这个listview被放在了一个FrameLayout中,其中还有一个和第二个头部的布局一样的布局,暂称为replacelayout,这个布局是被隐藏的,他就是滑动时用来替代悬浮头部的。当你滑动到第二个头部的时候,把replacelayout的visibility改成Visible,而真正的悬浮头部已经被滑动出了手机屏幕。
主要代码:
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_sticky);
- invis = (LinearLayout) findViewById(R.id.invis);
- strs = new String[100];
- for (int i = 0; i < 20; i++) {
- strs[i] = "data-----" + i;
- }
- lv = (ListView) findViewById(R.id.lv);
- View header = View.inflate(this, R.layout.stick_header, null);//头部内容
- lv.addHeaderView(header);//添加头部
- lv.addHeaderView(View.inflate(this, R.layout.stick_action, null));//ListView条目中的悬浮部分 添加到头部
- lv.setAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, strs));
- lv.setOnScrollListener(new OnScrollListener() {
- @Override
- public void onScrollStateChanged(AbsListView view, int scrollState) {
- }
- @Override
- public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
- if (firstVisibleItem >= 1) { //头部部分是0,悬浮部分是1
- invis.setVisibility(View.VISIBLE);
- } else {
- invis.setVisibility(View.GONE);
- }
- }
- });
- }
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- <TextView
- android:id="@+id/title"
- android:layout_width="match_parent"
- android:layout_height="30dp"
- android:background="#332b3b"
- android:gravity="center"
- android:text="标题"
- android:textColor="#ffffff" />
- <FrameLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_below="@id/title" >
- <ListView
- android:id="@+id/lv"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
- <LinearLayout
- android:id="@+id/invis"
- android:layout_width="fill_parent"
- android:layout_height="50dp"
- android:background="#ccedc7"
- android:orientation="horizontal"
- android:visibility="gone" >
- <TextView
- android:id="@+id/tv"
- android:layout_width="match_parent"
- android:layout_height="50dp"
- android:gravity="center"
- android:text="悬浮部分" />
- </LinearLayout>
- </FrameLayout>
- </RelativeLayout>