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

Android 筆記:讓 ListView 隨捲動自動顯示與隱藏頂部布局

編輯:關於 Android 程式設計

學 Android 一段時間了,學過的東西老是忘,於是決定寫成筆記逼自己整理一次。這次要做的是一個常見互動:往上捲動時 Toolbar 收起,往下捲動時滑回來。

先認識 ObjectAnimator

這個效果會用到 ObjectAnimator,先把它搞清楚。

ObjectAnimator 屬於屬性動畫,是 ValueAnimator 的子類。它本身就包含了時間引擎與數值計算,所以能直接為某個物件的某個屬性製作動畫。

常用的 ofInt、ofFloat 方法,參數是:(操作物件, 屬性名稱, 動畫起始值, 動畫結束值)。屬性名稱一般是 alpha、translationY、translationX、rotationX、rotationY、scaleX、scaleY。

ObjectAnimator animator = ObjectAnimator.ofFloat(imageBall, "alpha", 0f, 1f);
animator.setDuration(500).start();   // 透明度 0 → 1,歷時 500ms

步驟一:關掉預設 ActionBar

因為要用自訂的 Toolbar,先在 styles.xml 中改用 NoActionBar 主题:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

步驟二:加一個 HeaderView 墊高

避免第一個 item 被 Toolbar 遮住:

View header = new View(this);
header.setLayoutParams(new AbsListView.LayoutParams(
        AbsListView.LayoutParams.MATCH_PARENT,
        (int) getResources().getDimension(R.dimen.abc_action_bar_default_height_material)));
listView.addHeaderView(header);

這裡用 R.dimen.abc_action_bar_default_height_material 取得 ActionBar 的標準高度,讓墊高值與 Toolbar 一致。

步驟三:取得系統的最小滑動距離

mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();

位移超過這個值,才算一次有效滑動,可以避免手指輕微抖動就觸發動畫。

步驟四:判斷滑動方向

private void scorllEvent() {
    listView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mFirstY = (int) motionEvent.getY();
                    break;

                case MotionEvent.ACTION_MOVE:
                    mCurrentY = (int) motionEvent.getY();
                    if (mCurrentY - mFirstY > mTouchSlop) {
                        direction = 0;   // 向下滑動
                    } else {
                        direction = 1;   // 向上滑動
                    }
                    if (direction == 1) {
                        if (mShow) {
                            ToolbarAnim(0);
                            mShow = false;
                        }
                    } else {
                        if (!mShow) {
                            ToolbarAnim(1);
                            mShow = true;
                        }
                    }
                    break;
            }
            return false;   // 不消費事件,讓 ListView 正常捲動
        }
    });
}

關鍵是最後那個 return false。若回傳 true,事件會被攔下,ListView 就捲不動了——我們只是「旁聽」手勢,不是要接管它。

步驟五:控制動畫

private void ToolbarAnim(int i) {
    if (animator != null && animator.isRunning()) {
        animator.cancel();
    }
    if (i == 0) {
        // 顯示:translationY 回到 0
        animator = ObjectAnimator.ofFloat(toolbar, "translationY",
                toolbar.getTranslationY(), 0);
    } else {
        // 隱藏:translationY 移到 -height
        animator = ObjectAnimator.ofFloat(toolbar, "translationY",
                toolbar.getTranslationY(), -toolbar.getHeight());
    }
    animator.start();
}

動畫前先檢查並取消上一個仍在跑的動畫,否則連續滑動會讓兩段動畫互相打架。

效果與驗證

上滑(隱藏):

下滑(顯示):

用日誌印出位移可以驗證:

從輸出可以看到,上滑時 translationY 由 0 走到 -56,下滑時再由 -56 回到 0,與預期一致。

版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

完整程式碼

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List<String> list;
    private Toolbar toolbar;

    private int mTouchSlop;        // 系統認為的最小滑動距離
    private int mFirstY;           // 第一次觸摸的位置
    private int mCurrentY;         // 當前觸摸的 Y 軸位置
    private boolean mShow = true;  // 當前是否顯示
    private int direction;
    private ObjectAnimator animator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        listView = (ListView) findViewById(R.id.list_view);

        list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(i + "");
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this, android.R.layout.simple_expandable_list_item_1, list);
        listView.setAdapter(adapter);

        // 墊一個與 ActionBar 等高的 HeaderView,避免首項被 Toolbar 遮住
        View header = new View(this);
        header.setLayoutParams(new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT,
                (int) getResources().getDimension(
                        R.dimen.abc_action_bar_default_height_material)));
        listView.addHeaderView(header);

        mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
        scorllEvent();
    }

    private void scorllEvent() {
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mFirstY = (int) motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mCurrentY = (int) motionEvent.getY();
                        if (mCurrentY - mFirstY > mTouchSlop) {
                            direction = 0;   // 向下
                        } else {
                            direction = 1;   // 向上
                        }
                        if (direction == 1) {
                            if (mShow) {
                                ToolbarAnim(0);
                                mShow = false;
                            }
                        } else {
                            if (!mShow) {
                                ToolbarAnim(1);
                                mShow = true;
                            }
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void ToolbarAnim(int i) {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        if (i == 0) {
            animator = ObjectAnimator.ofFloat(toolbar, "translationY",
                    toolbar.getTranslationY(), 0);
        } else {
            animator = ObjectAnimator.ofFloat(toolbar, "translationY",
                    toolbar.getTranslationY(), -toolbar.getHeight());
        }
        animator.start();
    }
}

可以更好的地方

  • 用 OnScrollListener 取代 OnTouchListener 更直觀:直接讀 dy 的正負就能判斷方向,不必自己算位移,也不會與 ListView 的滑動判定打架。
  • 目前每次 ACTION_MOVE 都重新計算,容易在同一段滑動中反覆觸發。實務上建議記錄方向變化才啟動動畫。
  • Toolbar 隱藏後若頁面還有可點擊区域,記得確認沒有被懸空的 view 擋住。
  • 若使用 CoordinatorLayout 搭配 AppBarLayout,這整套自製邏輯可以省下來,官方組件已經處理好嵌套捲動與互動細節。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved