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

Android 實現 Tab 欄懸浮吸頂的兩種方案對比

編輯:關於 Android 程式設計

如上圖,「分類 / 排序 / 篩選」這一排會滾到頂部後固定住,狀態隨 ScrollView 的滾動而變化。Tab 欄不再被滑出屏幕,用戶切換分類時不必往回滾,交互體驗提升明顯。

前置條件:拿到滑動距離

整個效果的基礎是監聽 ScrollView 的滾動距離。ScrollView 本身沒有直接的距離回調,需要通過 ViewTreeObserver 或自定義 ScrollView 的 onScrollChanged 來間接獲取。

兩種實現思路

  • 方案一:用 WindowManager 動態添加一個懸浮 View 蓋在頂部;
  • 方案二:隨 ScrollView 滾動,不斷重設 Tab 欄的布局位置。

方案一:WindowManager 懸浮窗

Activity 布局 activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/rl_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary">
        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/new_img_back" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/app_name"
            android:textColor="@android:color/white"
            android:textSize="18sp" />
    </RelativeLayout>

    <com.yuqirong.tabsuspenddemo.view.MyScrollView
        android:id="@+id/mScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#cccccc"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/iv_pic"
                android:layout_width="match_parent"
                android:layout_height="180dp"
                android:scaleType="centerCrop"
                android:src="@drawable/ic_bg_personal_page" />

            <include layout="@layout/tab_layout" />

            <!-- 下面這一堆空白 LinearLayout 只是為了把頁面撐長,方便看效果 -->
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="90dp"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginTop="15dp"
                android:background="@android:color/white"
                android:orientation="horizontal">
            </LinearLayout>
            <!-- 重複若干個即可 -->
        </LinearLayout>
    </com.yuqirong.tabsuspenddemo.view.MyScrollView>
</LinearLayout>

Tab 欄布局 tab_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ll_tab"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="@color/colorPrimary"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="分類"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="排序"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="篩選"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
</LinearLayout>

布局大致長這樣:

onCreate 中做準備:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
    mScrollView = (MyScrollView) findViewById(R.id.mScrollView);
    mScrollView.setOnScrollListener(this);
    ll_tab = (LinearLayout) findViewById(R.id.ll_tab);
    windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
}

這裡刻意調用了 getSupportActionBar().hide() 去掉標題欄。原因很實際:懸浮窗的 y 坐標是相對屏幕原點的,若保留標題欄,就得在計算時額外加上它的高度。當然保留也行,把那個高度補回去就好。

在 onWindowFocusChanged 中記錄關鍵尺寸:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        tabHeight = ll_tab.getHeight();
        tabTop = ll_tab.getTop();
        scrollTop = mScrollView.getTop();
    }
}

必須等視圖完成布局後才能拿到準確的高度,所以放在這個回調裡而不是 onCreate。

在滾動回調中控制懸浮窗的顯示與移除:

@Override
public void onScroll(int scrollY) {
    if (scrollY > tabTop) {
        if (!isShowWindow) {
            showWindow();
        }
    } else {
        if (isShowWindow) {
            removeWindow();
        }
    }
}

// 顯示懸浮窗
private void showWindow() {
    if (ll_tab_temp == null) {
        ll_tab_temp = LayoutInflater.from(this).inflate(R.layout.tab_layout, null);
    }
    if (layoutParams == null) {
        layoutParams = new WindowManager.LayoutParams();
        layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.gravity = Gravity.TOP;
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = tabHeight;
        layoutParams.x = 0;
        layoutParams.y = scrollTop;
    }
    windowManager.addView(ll_tab_temp, layoutParams);
    isShowWindow = true;
}

// 移除懸浮窗
private void removeWindow() {
    if (ll_tab_temp != null) {
        windowManager.removeView(ll_tab_temp);
    }
    isShowWindow = false;
}

記得申請權限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

效果:

方案一的致命問題

這種做法依賴 SYSTEM_ALERT_WINDOW 權限。從 Android 6.0 開始,這屬於特殊權限,需要引導用戶手動到系統設置裡開啟「顯示在其他應用上層」。一旦用戶拒絕,整個懸浮功能就形同虛設。此外懸浮窗是獨立於 Activity 的窗口,Activity 銷毀時若忘記 removeView() 還會引發 BadTokenException。

方案二:在原布局內做替換(更推薦)

更穩妥的思路是完全不離開 Activity 的視圖樹:

  1. 在 Tab 欄在 ScrollView 中的原始位置佔一個等高占位 View;
  2. 在 ScrollView 外層(與它同級的容器)預先放一個隐藏的 Tab 副本;
  3. 滾動距離超過 Tab 欄距頂部的距離時,隱藏原位 Tab、顯示外層副本;反之恢復。

這種做法不需要任何特殊權限,也不存在窗口洩漏風險,是電商類 App 的主流選擇。若希望切換更絲滑,還可以在临界点附近讓兩者做透明度交叉淡變,避免「啪」一下的突兀感。

兩種方案對比下來:方案一寫得快,但權限依賴讓它在正式產品中基本不可用;方案二多寫幾十行,卻換來了可控性和穩定性,值得投入。

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