編輯:關於 Android 開發
本文介紹如何借助 View 的 OnTouchListener 介面監聽 ListView 的滑動,透過比較與上次座標的大小判斷滑動方向,進而決定顯示或隱藏對應的布局,並配上平滑的動畫效果。
首先給 ListView 增加一個 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)));
mListView.addHeaderView(header);
其中 R.dimen.abc_action_bar_default_height_material 為系統 ActionBar 的高度。
定義一個 mTouchSlop 變量,取得系統認為的最低滑動距離:
mTouchSlop=ViewConfiguration.get(this).getScaledTouchSlop();
接著判斷滑動事件:
bbsListView.setOnTouchListener(new OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mFirstY=event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurrentY=event.getY();
if(mCurrentY-mFirstY>mTouchSlop) direction=0; // 向下滑動
else if(mFirstY-mCurrentY>mTouchSlop) direction=1; // 向上滑動
if(direction==1) {
if(mShow) { toolbarAnim(1); mShow=!mShow; } // 隱藏
} else if(direction==0) {
if(!mShow) { toolbarAnim(0); mShow=!mShow; } // 展示
}
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
屬性動畫部分,透過 ObjectAnimator 對位移(translationY)與透明度(alpha)做動畫:
protected void toolbarAnim(int flag) {
if(set!=null && set.isRunning()) { set.cancel(); }
if(flag==0) {
mAnimator1=ObjectAnimator.ofFloat(mToolbar, "translationY", linearView.getTranslationY(),0);
mAnimator2=ObjectAnimator.ofFloat(mToolbar, "alpha", 0f,1f);
} else if(flag==1) {
mAnimator1=ObjectAnimator.ofFloat(mToolbar, "translationY", linearView.getTranslationY(),-linearView.getHeight());
mAnimator2=ObjectAnimator.ofFloat(mToolbar, "alpha", 1f,0f);
}
set=new AnimatorSet();
set.playTogether(mAnimator1,mAnimator2);
set.start();
}
使用時 theme 要用 NoActionBar 的,否則會引起衝突,同時引入編譯:
dependencies{
compile fileTree(include:['*.jar'],dir:'libs')
compile 'com.android.support:appcompat-v7:21.0.3'
}
當要隱藏和顯示的組件不是 Toolbar,而是自定義布局 myView 時,需要注意幾點:
(1)布局要用相對布局,讓自定義布局懸浮在 ListView 上方;
(2)避免第一個 Item 被 myView 遮擋,給 ListView 增加一個 HeaderView。此時需要測量 myView 的高度,要用下面這種方法,把任務 post 到 UI 執行緒中,否則執行會出錯:
final View header=new View(this);
header.post(new Runnable() {
public void run() {
header.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, myView.getHeight()));
}
});
其餘邏輯與 Toolbar 相同。
Android Tab 頁籤實作:ViewPager 搭配 PagerTabStrip
Android Tab 頁籤實作:ViewPager 搭配 PagerTabStrip 要做「滑動切頁 + 點標籤切頁」的頂部頁籤,最省事的做法是 ViewPager 搭
Android Studio 系列教學(一):下載、安裝與打造第一個 Hello World
Android Studio 系列教學(一):下載、安裝與打造第一個 Hello World 本系列文章大致涵蓋以下主題,本文為第一篇: 系列一:下載與安裝、背景介紹、
Android 主題 Theme 與樣式 Style 完全解析
每家公司出品的 App 都有統一的視覺風格,這背後離不開 theme 與 style。它們不僅能統一外觀,還能實現 Activity 切換動畫等效果,既簡潔又能大幅減少重
用 Kotlin 開發 Android 應用:從工程配置到代碼轉換的完整入門
用 Kotlin 開發 Android 應用:從工程配置到代碼轉換的完整入門 一、Kotlin 是什麼 Kotlin 是一門基於 JVM 的編程語言,正在成長為 Andr