編輯:關於 Android 程式設計
下拉更新、上拉載入更多,這類功能的前提都是「先知道使用者滾到哪裡了」。ScrollView 沒有現成的 OnScrollListener(早期版本更是如此),最直接的作法是自己攔下觸碰事件,在 ACTION_MOVE 階段做判斷。
這段邏輯之所以容易寫錯,多半是把三個值搞混:
mScrollView.getChildAt(0).getMeasuredHeight():捲動內容的完整高度。畫面外還沒看到的那一段也算在裡面。view.getScrollY():已經被捲出頂端的距離,也就是目前捲動到的位置。view.getHeight():ScrollView 本身的可見高度,即一個螢幕能看到的範圍。把三者湊起來,判斷式就非常直觀:scrollY == 0 是頂端,scrollY + height == 內容高度 就是到底了。
<RelativeLayout 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" >
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</ScrollView>
</RelativeLayout>
package cn.testscrollview;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ScrollView;
import android.app.Activity;
public class MainActivity extends Activity {
private ScrollView mScrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setOnTouchListener(new TouchListenerImpl());
}
private class TouchListenerImpl implements OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_MOVE:
int scrollY = view.getScrollY();
int height = view.getHeight();
int contentHeight = mScrollView.getChildAt(0).getMeasuredHeight();
if (scrollY == 0) {
System.out.println("滑動到了頂端 scrollY=" + scrollY);
}
if (scrollY + height == contentHeight) {
System.out.println("滑動到了底部 scrollY=" + scrollY);
System.out.println("滑動到了底部 height=" + height);
System.out.println("內容高度=" + contentHeight);
}
break;
default:
break;
}
return false; // 交回事件鏈,不阻斷 ScrollView 自身的捲動
}
}
}
第一,return false 是必要的。回傳 true 會把事件吃掉,ScrollView 就再也捲不動了。
第二,用等號比對邊界其實有風險:快速滑動時 scrollY 可能一次跳過精確值,導致永遠觸發不到。比較穩健的寫法是改用 >= 與 <=,或搭配一個布林旗標避免同一邊界被連續觸發多次。若專案已鎖定 API 23 以上,直接掛 ViewTreeObserver.OnScrollChangedListener 或 NestedScrollView 會更省事。
Android 使用 AIDL 實作跨進程通訊(IPC)完整教學
前言:在做一件事之前,千萬別先覺得它很難。還沒開始就先在內心產生恐懼,只會阻礙你的進步——往往真的動手做完,才發現沒那麼複雜。 一、AIDL 是什麼?為什麼需要它? A
AsyncTask 執行流程深度解析
為什麼要使用異步任務? Android 是單執行緒模型、多執行緒的作業系統,因此耗時操作必須放在非主執行緒中執行,避免阻塞 UI。 AsyncTask 為何而生? 它解決
Android 高仿 QQ 圖片選擇器實現詳解
做一款需要選擇本地圖片的 APP 時,首先想到的無疑是系統相冊。但 Android 手機五花八門,加上手機像素不斷提升、大圖無法回傳等異常因素,導致適配機型相當困難。微信
深入原理:Android 創建桌面快捷方式 Shortcut
網路上寫過創建桌面快捷方式的文章很多,但大部分只講了「怎麼用」,其實技術操作起來都很簡單,問題是下次你還記得嗎?根本原因還是不清楚原理。今天我就來講講 shortcut