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

Android 事件傳遞機制解析:手把手實作仿下拉刷新

編輯:關於 Android 程式設計

概述

在 Android 中,事件主要包含點按、長按、拖曳、滑動等,其中點按又分單擊與雙擊,還包含單指與多指操作。不論是哪一種,所有事件都可拆解為三個基礎動作:按下(ACTION_DOWN)、移動(ACTION_MOVE)、抬起(ACTION_UP)。

與 touch 事件相關的三個核心方法如下:

public boolean dispatchTouchEvent(MotionEvent ev);   // 用來分派事件
public boolean onInterceptTouchEvent(MotionEvent ev); // 用來攔截事件
public boolean onTouchEvent(MotionEvent ev);          // 用來處理事件

關鍵在於 onInterceptTouchEvent():它決定是否允許 Touch 事件繼續向下傳遞給子控件。一旦回傳 true(代表事件由目前的 ViewGroup 處理),向下傳遞之路就被截斷,所有子控件都不再有機會參與事件,同時事件會交給本身的 onTouchEvent() 處理;若回傳 false,則把事件交給子控件的 onInterceptTouchEvent()。而 dispatchTouchEvent() 是事件分派的總入口,onTouchEvent() 則是真正消費事件的地方。

Demo:模擬下拉刷新

我們自訂一個繼承自 FrameLayout 的 MyFreshLayout,並重寫上述三個方法,來實作一個簡單的下拉手勢:手指下滑時讓 ListView 跟著位移,放手後再用屬性動畫讓它歸位。

public class MyFreshLayout extends FrameLayout {
    private ListView mListView;
    private float oldY;
    private float y;

    public MyFreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View header = inflater.inflate(R.layout.header, null);
        addView(header);
        mListView = (ListView) inflater.inflate(R.layout.content, null);
        addView(mListView);
        ArrayAdapter<String> adapter = new ArrayAdapter(context,
            android.R.layout.simple_list_item_1,
            new String[]{ "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P" });
        mListView.setAdapter(adapter);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // 當列表已在頂部時,攔截事件交給自己處理,模擬下拉
        if (mListView.getFirstVisiblePosition() == 0) {
            View firstView = mListView.getChildAt(0);
            if (firstView.getY() >= 0) {
                return true;
            }
        }
        return super.onInterceptHoverEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                oldY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                y = event.getY();
                float distance = y - oldY;
                mListView.setTranslationY(mListView.getTranslationY() + distance);
                oldY = y;
                break;
            case MotionEvent.ACTION_UP:
                ObjectAnimator.ofFloat(mListView, "translationY",
                    mListView.getTranslationY(), 0).setDuration(300).start();
                break;
        }
        return true;
    }
}

header 作為首部布局,初始時被 ListView 覆蓋住:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="30dp"
        android:text="刷新" />
</FrameLayout>

content 則是主要內容:

<ListView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/listView_downDrap"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff" />

主版面把自訂元件放進來:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.example.administrator.selfishgroupview.my_groupview.myfreshlayout
        android:id="@+id/MyFreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

MainActivity 只需取得這個自訂元件:

public class MainActivity extends Activity {
    private MyFreshLayout myFreshLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myFreshLayout = (MyFreshLayout) findViewById(R.id.MyFreshLayout);
    }
}

透過 this 示範,你應該能體會 dispatchTouchEvent、onInterceptTouchEvent 與 onTouchEvent 三者如何分工:分派、攔截、消費。掌握這條鏈路,就能輕鬆實作各種自訂的手勢交互。

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