編輯:關於 Android 程式設計
行動裝置幾乎成了每個人的隨身配備,而決定一個 App 好不好的,除了功能本身,使用者體驗與介面細節往往才是關鍵。最近在美團與大眾點評上看到一個很貼心的設計:往下滑動時,「立即搶購」那一欄會自動吸附在頂部導航列下方,隨時都能下單;往回滑動時它又乖乖回到原本的位置。這種吸頂效果自己動手做過一次,就會發現思路比想像中簡單。
觀察上面第二張圖:當「立即搶購」區塊向上滑到導航列下方時,它就貼在那裡不動,而底下的內容仍可繼續滾動;反向滑動時,它又跟著一起往下走。
拆解之後只有兩個動作:
於是問題變成:怎麼即時取得 ScrollView 的滾動距離?遺憾的是 ScrollView 本身並未提供滾動監聽,這部分必須自己補上。
為了示範方便,這裡直接用截圖當內容:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/buy_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/buy" />
</LinearLayout>
上方是導航列,下方是 ScrollView,裡頭依序放頭圖、立即搶購、以及其餘內容:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="45dip"
android:scaleType="centerCrop"
android:src="@drawable/navigation_bar" />
<com.example.meituandemo.MyScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/iamge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/pic"
android:scaleType="centerCrop" />
<include
android:id="@+id/buy"
layout="@layout/buy_layout" />
<ImageView ... />
<ImageView ... />
<ImageView ... />
</LinearLayout>
</com.example.meituandemo.MyScrollView>
</LinearLayout>
注意最外層的捲動容器不是 ScrollView,而是自訂的 MyScrollView。
public class MyScrollView extends ScrollView {
private OnScrollListener onScrollListener;
/** 用於手指離開後,持續追蹤 Y 距離是否還在變動 */
private int lastScrollY;
public MyScrollView(Context context) {
this(context, null);
}
public MyScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
/** 手指離開後,每隔 5ms 檢查滾動是否已停止 */
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int scrollY = MyScrollView.this.getScrollY();
if (lastScrollY != scrollY) {
lastScrollY = scrollY;
handler.sendMessageDelayed(handler.obtainMessage(), 5);
}
if (onScrollListener != null) {
onScrollListener.onScroll(scrollY);
}
}
};
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (onScrollListener != null) {
onScrollListener.onScroll(lastScrollY = getScrollY());
}
switch (ev.getAction()) {
case MotionEvent.ACTION_UP:
// 抬手後可能還在滑,交給 handler 持續追蹤
handler.sendMessageDelayed(handler.obtainMessage(), 5);
break;
default:
break;
}
return super.onTouchEvent(ev);
}
public interface OnScrollListener {
void onScroll(int scrollY);
}
}
這段程式的巧妙之處在於處理了「手指離開但畫面仍在滑」的情況。如果只在 onTouchEvent() 中監聽,使用者一抬手就再也收不到滾動事件,吸頂時機自然會錯。因此 ACTION_UP 時額外丟一個延遲訊息給 Handler,讓它每 5 毫秒比對一次 getScrollY():數值還在變就繼續排下一輪,不再變動就停止。
對外只需要呼叫 setOnScrollListener(),就能持續收到滾動距離。
public class MainActivity extends Activity implements OnScrollListener {
private MyScrollView myScrollView;
private LinearLayout mBuyLayout;
private WindowManager mWindowManager;
/** 螢幕寬度 */
private int screenWidth;
/** 懸浮層 View */
private static View suspendView;
/** 懸浮層參數 */
private static WindowManager.LayoutParams suspendLayoutParams;
/** 購買區塊高度 */
private int buyLayoutHeight;
/** myScrollView 距父容器頂部的距離 */
private int myScrollViewTop;
/** 購買區塊距父容器頂部的距離 */
private int buyLayoutTop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myScrollView = (MyScrollView) findViewById(R.id.scrollView);
mBuyLayout = (LinearLayout) findViewById(R.id.buy);
myScrollView.setOnScrollListener(this);
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
screenWidth = mWindowManager.getDefaultDisplay().getWidth();
}
/** 所有佈局繪製完成後,才能取得正確的高度與位置 */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
buyLayoutHeight = mBuyLayout.getHeight();
buyLayoutTop = mBuyLayout.getTop();
myScrollViewTop = myScrollView.getTop();
}
}
@Override
public void onScroll(int scrollY) {
if (scrollY >= buyLayoutTop) {
if (suspendView == null) {
showSuspend();
}
} else if (scrollY <= buyLayoutTop + buyLayoutHeight) {
if (suspendView != null) {
removeSuspend();
}
}
}
private void showSuspend() {
if (suspendView == null) {
suspendView = LayoutInflater.from(this).inflate(R.layout.buy_layout, null);
if (suspendLayoutParams == null) {
suspendLayoutParams = new WindowManager.LayoutParams();
suspendLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
suspendLayoutParams.format = PixelFormat.RGBA_8888;
suspendLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams.FLAG_NOT_FOCUSABLE;
suspendLayoutParams.gravity = Gravity.TOP;
suspendLayoutParams.width = screenWidth;
suspendLayoutParams.height = buyLayoutHeight;
suspendLayoutParams.x = 0;
suspendLayoutParams.y = myScrollViewTop;
}
}
mWindowManager.addView(suspendView, suspendLayoutParams);
}
private void removeSuspend() {
if (suspendView != null) {
mWindowManager.removeView(suspendView);
suspendView = null;
}
}
}
整個判斷只有兩條界線:buyLayoutTop 是懸浮層該出現的門檻,buyLayoutTop + buyLayoutHeight 是它該消失的位置。而懸浮層的實作完全是靠 WindowManager——addView() 加一個浮在上方的 View,removeView() 把它移掉。
別忘了在 AndroidManifest.xml 加上權限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
執行結果如下:
上述实现能跑、思路也清楚,但用在正式專案前,有幾個地方值得重新評估:
TYPE_APPLICATION_OVERLAY,且 SYSTEM_ALERT_WINDOW 需引導使用者到系統設定手動授予「顯示在其他應用程式上層」權限,單純在 Manifest 宣告已不足夠。include 出來的懸浮 View,一開始設為 INVISIBLE,需要時切換可見性並做 translation 動畫。CoordinatorLayout 搭配 AppBarLayout 與 CollapsingToolbarLayout 就能原生實現吸頂與收合,不必自己算座標。setOnScrollChangeListener(),省掉自訂 ScrollView 的功夫,且能與 RecyclerView 等巢狀捲動元件協同運作。onCreate() 中呼叫 getHeight() 一律回傳 0,這是很多人卡住的地方;本例用 onWindowFocusChanged(),實務上也可以改用 ViewTreeObserver 或 doOnLayout。理解「監聽滾動距離 → 與門檻比較 → 顯示或移除覆蓋層」這個骨架之後,無論是自己實作還是改用官方元件,都能快速做出流暢自然的吸頂效果。
Android Service 與 IntentService 的差異
Service 是 Android 四大元件之一,適合執行不需要使用者互動的背景工作。它沒有畫面,但可由 Activity 或其他元件啟動與控制。Service 生命週期
Android 接入微信支付的完整流程與常見問題
微信支付是 Android 應用常見的變現方式之一。接入過程看似簡單,但涉及開放平台配置、簽名校驗、後端下單、客戶端調起以及支付回調等多個環節。本文整理 Android
應用耗電分析與優化:Battery Historian 實戰指南
在 Android 專案裡,電量消耗一直是最難量化、卻又最被用戶敏感的指標。使用者未必說得出你的產品有多少功能,但只要手機待機掉得比別人快,卸載的決定往往下得毫不留情。指
Android 傳感器入門(二):方向傳感器與指南針實作
本節引言 上一節我們學過傳感器的基本概念與通用使用套路,本節接著談方向傳感器的用法。 一、三維座標系的概念 Android 平台的傳感器框架通常以一組標準的三維座