Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 FlexibleListView:打造 QQ 空間式的阻尼下拉與漸變菜單欄

編輯:關於 Android 程式設計

上一則 UI 筆記寫完自定義 Dialog 之後,因為公司封閉開發和封網,這個系列中斷了一段時間,這裡補上。最近專案有個需求:做一個類似 QQ 空間的效果——菜單欄透明度隨滾動漸變,頂部下拉時帶阻尼回彈。試著做了一版,基本達到了預期:

觀察 QQ 空間的行為可以拆出兩個關鍵:往上滾動時,菜單欄透明度隨滾動距離增大而遞增,直到完全不透明,反向滾動則逐漸透明;滾到頂部後繼續下拉會出現拉伸,手指離開後阻尼回彈。於是決定用重寫 ListView 的方式來複刻。

動手之前要先想清楚兩件事:

1)菜單欄透明度漸變怎麼做
透明度既然隨滾動距離變化,問題就轉化成了「如何取得 ListView 的滾動距離」。

2)阻尼拉伸與回彈怎麼做
前提是先滾到頂部,此時繼續下滑要讓第一個 Child 產生位移來模擬拉伸,手指離開後再回到初始狀態。

一、取得滾動距離:HeaderView 是關鍵

直覺做法是拿第一個可見 Item 的 getTop(),但 ListView 有複用機制,這個值不可靠。可行的切入點是 HeaderView——它在 ListView 中並不參與複用。

先釐清含 HeaderView 時的三種滾動狀態:

狀態一是初始狀態(恰好頂到最上方),此時 HeaderView 的 getTop() 為 0;狀態二是滾動中,HeaderView 還沒完全離開可視邊界,getTop() 回傳負數,絕對值落在 0 到 HeaderView 高度之間;狀態三是 HeaderView 完全滾出邊界,getTop() 的絕對值等於 HeaderView 高度(此後可視為固定在頂部)。

新建 FlexibleListView,flexible 取「靈活、多樣」之意,因為它既要漸變也要阻尼。先補齊構造方法:

 public class FlexibleListView extends ListView { public FlexibleListView(Context context) { super(context); } public FlexibleListView(Context context, AttributeSet attrs) { super(context, attrs); } public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(21) public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } } 

要拿到 HeaderView,這裡有個小技巧:addHeaderView 最終都會走到 addHeaderView(View v, Object data, boolean isSelected),所以重寫它就能攔到傳入的 View。由於 HeaderView 的添加順序即繪製順序,第一個進來的就是我們要的那個,用一個是否為空的判斷即可鎖定:

 public class FlexibleListView extends ListView { private View mHeaderView; private int mMaxScrollHeight; public FlexibleListView(Context context) { super(context); } public FlexibleListView(Context context, AttributeSet attrs) { super(context, attrs); } public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(21) public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public void addHeaderView(View v, Object data, boolean isSelectable) { super.addHeaderView(v, data, isSelectable); if(null == mHeaderView) { mHeaderView = v; mMaxScrollHeight = mHeaderView.getLayoutParams().height; } } } 

mMaxScrollHeight 代表 HeaderView 允許滾動的最大距離,這裡直接用它的高度。超過這個值就把菜單欄設為全不透明,否則按比例算 alpha。

二、滾動時機:重寫 onScrollChanged

常見做法是掛 OnScrollListener,可行,但這次換個思路。翻 AbsListView 源碼會發現,回調的觸發點在 invokeOnItemScrollListener():

 void invokeOnItemScrollListener() { if (mFastScroll != null) { mFastScroll.onScroll(mFirstPosition, getChildCount(), mItemCount); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount); } onScrollChanged(0, 0, 0, 0); // dummy values, View's implementation does not use these. } 

仔細看最後一行:無論有沒有設置監聽器,View 的 onScrollChanged() 都會被呼叫。既然如此,直接重寫它就好,省掉一層監聽器。

三、透明度漸變的實作

還需要一個代表菜單欄的屬性,以及一個對外綁定的方法。無論是 ActionBar、ToolBar 還是自定義 ViewGroup 模擬的標題欄,都能傳進來:

 public class FlexibleListView extends ListView { private View mActionBar; private View mHeaderView; private int mMaxScrollHeight; private Drawable mActionBarBackground; public FlexibleListView(Context context) { super(context); } public FlexibleListView(Context context, AttributeSet attrs) { super(context, attrs); } public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(21) public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if(null != mActionBarBackground) { mActionBarBackground.setAlpha(evaluateAlpha(Math.abs(mHeaderView.getTop()))); } } @Override public void addHeaderView(View v, Object data, boolean isSelectable) { super.addHeaderView(v, data, isSelectable); if(null == mHeaderView) { mHeaderView = v; mMaxScrollHeight = mHeaderView.getLayoutParams().height; } } private int evaluateAlpha(int t) { if (t >= mMaxScrollHeight) { return 255; } return (int) (255 * t /(float) mMaxScrollHeight); } public void bindActionBar(View actionBar) { if(null != actionBar) { mActionBar = actionBar; mActionBarBackground = actionBar.getBackground(); if(null == mActionBarBackground) { mActionBarBackground = new ColorDrawable(Color.TRANSPARENT); } mActionBarBackground.setAlpha(0); if(Build.VERSION.SDK_INT >= 16) { mActionBar.setBackground(mActionBarBackground); } else { mActionBar.setBackgroundDrawable(mActionBarBackground); } } } public void bindActionBar(ActionBar actionBar) { if(null != actionBar) { // TODO 自行實作,ActionBar 實現漸變需要設置 WindowFeature } } } 

幾個實作細節:alpha 值域是 0~255,0 全透明、255 全不透;evaluateAlpha() 只做一次線性換算,超過最大滾動距離就飽和在 255。另外要注意 Drawable 是被共享的,直接改 alpha 會影響所有用到同一 Drawable 的地方,若菜單欄背景與別處共用,建議先 mutate 一份。

佈局很簡單,FrameLayout 讓菜單欄浮在列表之上:

 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/action_bar_height" android:background="#aabbcc" android:clickable="true" android:orientation="vertical" android:paddingLeft="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:drawableLeft="@mipmap/back" android:text="動態" android:textColor="#b8e7fe" android:textSize="17sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="好友動態" android:textColor="#b8e7fe" android:textSize="17sp" /> </FrameLayout>
 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.llew.wb.git.qqzone.FlexibleListView android:id="@+id/flexible_list_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="none"></com.llew.wb.git.qqzone.FlexibleListView> <include android:id="@+id/custom_action_bar" layout="@layout/action_bar_layout"/> </FrameLayout> 
 public class MainActivity extends AppCompatActivity { private FlexibleListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initGlobalParams(); } private void initGlobalParams() { mListView = (FlexibleListView) findViewById(R.id.flexible_list_view); View mFlexibleHeaderView = new View(getApplicationContext()); mFlexibleHeaderView.setBackgroundColor(Color.parseColor("#bbaacc")); int height = getResources().getDimensionPixelSize(R.dimen.header_height); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, height); mFlexibleHeaderView.setLayoutParams(params); final View actionBar = findViewById(R.id.custom_action_bar); mListView.bindActionBar(actionBar); mListView.addHeaderView(mFlexibleHeaderView); mListView.setAdapter(new Adapter()); } static class Adapter extends BaseAdapter { @Override public int getCount() { return 80; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView = new TextView(parent.getContext()); textView.setPadding(50, 50, 50, 50); textView.setText(position + 10 + ""); return textView; } } } 

跑一下:

漸變符合預期,接著做阻尼。

四、阻尼拉伸與回彈

直覺做法是重寫 onTouchEvent 系列方法,在 DOWN/MOVE/UP/CANCEL 分支裡各自處理。可行,但比接下來的方式繁瑣得多。

這裡採用的是 View 的 overScrollBy()。它是 2.3 之後才加入的 API,關於向下相容:一方面公司 App 只支援 3.0 以上,另一方面 2.3 及更早版本的市佔已可忽略,因此不再考慮。

先讀一下它的註釋:

 /** * Scroll the view with standard behavior for scrolling beyond the normal * content boundaries. Views that call this method should override * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the * results of an over-scroll operation. * * @param deltaX Change in X in pixels * @param deltaY Change in Y in pixels * @param scrollX Current X scroll value in pixels before applying deltaX * @param scrollY Current Y scroll value in pixels before applying deltaY * @param scrollRangeX Maximum content scroll range along the X axis * @param scrollRangeY Maximum content scroll range along the Y axis * @param maxOverScrollX Number of pixels to overscroll by in either direction * @param maxOverScrollY Number of pixels to overscroll by in either direction * @param isTouchEvent true if this scroll operation is the result of a touch event. * @return true if scrolling was clamped to an over-scroll boundary */ protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { // ...... } 

註釋的重點:當 View 已經滾到邊界卻還在繼續同一方向的滾動時,才會觸發這個方法。換句話說,ListView、ScrollView 滾到底了還繼續滑,它就會被呼叫。

九個參數裡我們只需要兩個:deltaY 是 Y 軸的相對位移量——頂部繼續下拉時為負,底部繼續上拉時為正,正好可以用來判斷方向;isTouchEvent 為 true 表示手指還在螢幕上,false 表示已離開。

 @Override protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { if(null != mHeaderView) { if(isTouchEvent && deltaY < 0) { mHeaderView.getLayoutParams().height += Math.abs(deltaY / 3.0); mHeaderView.requestLayout(); } } return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent); } 

手指按住且向下拖時,動態增加 mHeaderView 的高度並重新配置,Header 裡的 ImageView 高度設為 MATCH_PARENT,就會跟著被撐開。這裡 deltaY 除以 3 是一個增長係數,用來讓拉伸變得「有阻尼感」,實務上可以對外開放這個值讓設計調整手感。

剩下的是復原。手指離開時要回到原位,而且必須用動畫,否則會顯得生硬:

 @Override public boolean onTouchEvent(MotionEvent ev) { if(null != mHeaderView) { int action = ev.getAction(); if(MotionEvent.ACTION_UP == action || MotionEvent.ACTION_CANCEL == action) { resetHeaderViewHeight(); } } return super.onTouchEvent(ev); } private void resetHeaderViewHeight() { ValueAnimator valueAnimator = ValueAnimator.ofInt(1); valueAnimator.setDuration(700); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final float f = animation.getAnimatedFraction(); mHeaderView.getLayoutParams().height -= f * (mHeaderView.getLayoutParams().height - mMaxScrollHeight); mHeaderView.requestLayout(); } }); valueAnimator.setInterpolator(new OvershootInterpolator()); valueAnimator.start(); } 

OvershootInterpolator 會讓回彈帶一點過衝,視覺上更接近 QQ 空間的手感;如果希望更「乾脆」,換成 DecelerateInterpolator 即可。

五、HeaderView 佈局

模擬 QQ 空間的頭圖:ImageView 撐滿並用 centerCrop,底部疊一排入口:

 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/header_height"> <ImageView android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/ttt" /> <LinearLayout android:layout_width="match_parent" android:layout_height="30dp" android:layout_gravity="bottom" android:background="#33333333" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="相冊" android:gravity="center" android:textColor="@android:color/white" /> <View android:layout_width="1dp" android:layout_height="20dp" android:background="#ffffff" /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="說說" android:gravity="center" android:textColor="@android:color/white" /> <View android:layout_width="1dp" android:layout_height="20dp" android:background="#ffffff" /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="個性化" android:gravity="center" android:textColor="@android:color/white" /> <View android:layout_width="1dp" android:layout_height="20dp" android:background="#ffffff" /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="\@ 與我相關" android:gravity="center" android:textColor="@android:color/white" /> </LinearLayout> </FrameLayout> 

scaleType 用 centerCrop 的理由:容器被撐高時圖片能等比放大填滿,不會露出空白邊。接著把 MainActivity 的初始化改成 inflate 這個佈局:

 void initGlobalParams() { mListView = (FlexibleListView) findViewById(R.id.flexible_list_view); View mFlexibleHeaderView = LayoutInflater.from(this).inflate(R.layout.flexible_header_layout, mListView, false); AbsListView.LayoutParams params = (AbsListView.LayoutParams)mFlexibleHeaderView.getLayoutParams(); if(null == params) { params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT); } params.height = getResources().getDimensionPixelSize(R.dimen.header_height); mFlexibleHeaderView.setLayoutParams(params); final View actionBar = findViewById(R.id.custom_action_bar); mListView.bindActionBar(actionBar); mListView.addHeaderView(mFlexibleHeaderView); mListView.setAdapter(new Adapter()); } 

跑起來看:

總結一下這次的兩個抓手:一是 2.3 之後提供的 overScrollBy()(若要相容更早版本得自己實作一套類似邏輯),二是 ImageView 的 ScaleType 屬性——centerCrop 讓頭圖在高度變化時始終填滿,是阻尼效果能成立的關鍵。另外提醒一點:如果這個效果要用在 Android 12 以上的專案,下拉手勢可能與系統的預測式返回、auncher 的滾動行為相互干擾,實測時最好覆蓋幾種機型。

原文鏈接:https://blog.csdn.net/llew2011/article/details/51559694

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved