標籤:
原文地址:https://developer.android.com/training/gestures/viewgroup.html
在ViewGroup中處理觸摸事件要格外小心,因為在ViewGroup中有很多子View,而這些子View對於不同的觸摸事件來說是不同的目標。要確保每個View都正確的接收了相應的觸摸事件。
在ViewGroup中攔截觸摸事件
onInterceptTouchEvent()方法會在觸摸事件到達ViewGroup的表面時調用,這包括內部的子View。如果onInterceptTouchEvent()返回了true,那麼MotionEvent對象就會被攔截,這意味著該次事件不會傳給子View,而是會傳給ViewGroup本身的onTouchEvent()方法。
onInterceptTouchEvent()給了ViewGroup本身一個機會:在子View獲得任何事件之前一個攔截該事件的機會。如果onInterceptTouchEvent()返回了true,那麼原先處理該次事件的子View就會收到一個ACTION_CANCEL的事件,並且原先事件的剩餘事件都會被傳到該ViewGroup的onTouchEvent()方法中做常規處理。onInterceptTouchEvent()還可以返回false,這樣的話,該次事件則會通過View樹繼續向下傳遞,直到到達目標View為止,目標View會在自己的onTouchEvent()方法中處理該次事件。
在下面的範例程式碼中,類MyViewGroup繼承了ViewGroup,並包含了多個View,這些View我們在這裡稱之為子View,而MyViewGroup稱為父容器View。如果你在水平方向上滑動手指,那麼子View皆不會收到觸摸事件。MyViewGroup會通過滾動它的內部來實現觸摸事件的處理。不管如何,如果你按下了子View中的按鈕,或者在垂直方向上滑動,那麼ViewGroup則不會去攔截這些事件,因為子View是該次事件的目標View。在這些情況下,onInterceptTouchEvent()應該返回false,且MyViewGroup的onTouchEvent()方法也不會被調用。
public class MyViewGroup extends ViewGroup { private int mTouchSlop; ... ViewConfiguration vc = ViewConfiguration.get(view.getContext()); mTouchSlop = vc.getScaledTouchSlop(); ... @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ final int action = MotionEventCompat.getActionMasked(ev); // Always handle the case of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the scroll. mIsScrolling = false; return false; // Do not intercept touch event, let the child handle it } switch (action) { case MotionEvent.ACTION_MOVE: { if (mIsScrolling) { // We‘re currently scrolling, so yes, intercept the // touch event! return true; } // If the user has dragged her finger horizontally more than // the touch slop, start the scroll // left as an exercise for the reader final int xDiff = calculateDistanceX(ev); // Touch slop should be calculated using ViewConfiguration // constants. if (xDiff > mTouchSlop) { // Start scrolling! mIsScrolling = true; return true; } break; } ... } // In general, we don‘t want to intercept touch events. They should be // handled by the child view. return false; } @Override public boolean onTouchEvent(MotionEvent ev) { // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, // scroll this container). // This method will only be called if the touch event was intercepted in // onInterceptTouchEvent ... }}
這裡要注意,ViewGroup還提供了requestDisallowInterceptTouchEvent()方法。當子View不希望它的父容器及祖先容器攔截觸摸事件時,ViewGroup會在 onInterceptTouchEvent()方法中對其進行調用,從而判斷是否要攔截本次事件。
使用ViewConfiguration常量
在上面的代碼中使用了ViewConfiguration來初始化一個名為mTouchSlop的變數。你可以使用ViewConfiguration來訪問Android系統所使用的常用距離、速度及時間。
“mTouchSlop”引用了觸摸事件在被攔截之前手指移動的以像素為單位的距離。Touch slop經常被用來在使用者在執行觸摸操作時防止產生意外滾動。
ViewConfiguration的另外兩個常用方法是getScaledMinimumFlingVelocity()和getScaledMaximumFlingVelocity()。這兩個方法分別返回了用於初始化滾動的最小、最大的速度值。以每秒幾像素為單位:
ViewConfiguration vc = ViewConfiguration.get(view.getContext());private int mSlop = vc.getScaledTouchSlop();private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();...case MotionEvent.ACTION_MOVE: { ... float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { // A swipe occurred, do something }...case MotionEvent.ACTION_UP: { ... } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) { // The criteria have been satisfied, do something }}
擴充子View的觸控地區
Android提供的TouchDelegate使擴充子View的觸控地區成為了可能。這對於子View本身特別小,而它的觸控地區需要很大時很有用。如果需要的話,你也可以使用這種方式來縮小子View的觸控地區。
在下面的樣本中,ImageButton作為我們的”delegate view”(這裡的意思是需要父容器擴充觸控地區的那個View)。下面是樣本的布局檔案:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/parent_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/icon" /></RelativeLayout>
下面的代碼做了以下這些事情:
- 獲得父容器View,並Post一個Runnale對象到UI線程。這可以確保在調用getHitRect()方法之前父容器已經對子View完成了排布。getHitRect()會返回父容器座標內當前View的點擊矩陣(觸控地區)。
- 找到ImageButton,然後調用它的getHitRect()方法獲得該View的觸控邊界。
- 擴大ImageButton的觸控地區。
- 執行個體化一個TouchDelegate,將要擴充的觸控地區矩陣與要擴充觸控地區的ImageView作為參數傳入。
- 將TouchDelegate設定給父容器View,只有這樣做,我們所觸碰到的擴充地區才會被路由到子View上。
在TouchDelegate代理的範圍內,父容器View將會接收所有的觸摸事件。如果觸摸事件發生在子View本身的觸控地區內,那麼父容器View會將所有的觸摸事件傳給子View處理:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the parent view View parentView = findViewById(R.id.parent_layout); parentView.post(new Runnable() { // Post in the parent‘s message queue to make sure the parent // lays out its children before you call getHitRect() @Override public void run() { // The bounds for the delegate view (an ImageButton // in this example) Rect delegateArea = new Rect(); ImageButton myButton = (ImageButton) findViewById(R.id.button); myButton.setEnabled(true); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Touch occurred within ImageButton touch region.", Toast.LENGTH_SHORT).show(); } }); // The hit rectangle for the ImageButton myButton.getHitRect(delegateArea); // Extend the touch area of the ImageButton beyond its bounds // on the right and bottom. delegateArea.right += 100; delegateArea.bottom += 100; // Instantiate a TouchDelegate. // "delegateArea" is the bounds in local coordinates of // the containing view to be mapped to the delegate view. // "myButton" is the child view that should receive motion // events. TouchDelegate touchDelegate = new TouchDelegate(delegateArea, myButton); // Sets the TouchDelegate on the parent view, such that touches // within the touch delegate bounds are routed to the child. if (View.class.isInstance(myButton.getParent())) { ((View) myButton.getParent()).setTouchDelegate(touchDelegate); } } }); }}
Android官方開發文檔Training系列課程中文版:手勢處理之ViewGroup的事件管理