android 在ViewGroup中處理觸摸事件 [Managing Touch Events in a ViewGroup]

Managing Touch Events in a ViewGroup [在ViewGroup中管理觸摸事件]


在ViewGroup中處理觸摸事件需要特別注意,因爲通常一個ViewGroup都有子View, 它們都是不同觸摸事件的的對象。爲了確保每一個View都能正確接收意圖作用於它的觸摸事件,覆寫onInterceptTouchEvent()方法。

Intercept Touch Events in a ViewGroup [在一個ViewGroup中攔截觸摸事件]

每當在ViewGroup表面,也包括它的子view的表面上檢測到一個觸摸事件時,onInterceptTouchEvent()方法就會被調用。如果onInterceptTouchEvent()返回true, MotionEvents就會被攔截,意味着它將不會被傳遞到其子View,而是傳遞到父View的onTouchEvent()方法。

onInterceptTouchEvent()方法使得父View有機會在其子View之前接收觸摸事件。如果在父View的onInterceptTouchEvent()方法中返回true,在父View之前處理觸摸事件的子View將會收到一個ACTION_CANCEL,從那一個時刻開始,之後的事件將會發送到父View的onTouchEvent方法來正常處理。onInterceptTouchEvent()也能返回false,容易的發現觸摸事件將會順着view層級到通常接收並通過它們擁有的 onTouchEvent()方法處理這些觸摸事件的目標view。

在下面的代碼片段中,MyViewGroup類繼承於ViewGroup。MyViewGroup包含大量的子view。如果你在一個子view上水平拖動手指,子view將不會再獲得觸摸事件,MyViewGroup將會處理這些觸摸事件讓其內容滑動。然而,如果你點擊子view中的Button,或者在垂直方向滑動子view,父view不應該攔截這些觸摸事件,因爲這個子view是觸摸事件的目標。在這些情況下,onInterceptTouchEvent()應該返回false,MyViewGroup的onTouchEvent()方法將不會被調用。

ublic 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不想讓其父View和祖先View在onInterceptTouchEvent()中攔截觸摸事件時,這個ViewGroup會調用這個方法。

Use ViewConfiguration Constants [使用ViewConfiguration常量]

上面的代碼片段中使用當前的 ViewConfiguration 來初始化變量 mTouchSlop,你能夠使用ViewConfiguration類來訪問一些Android系統使用的常量,例如距離、速度和時間。

“Touch slop”是當用戶的觸摸事件被解釋爲滑動需要移動的最小像素距離。Touch slop典型的應用時爲了防止意外的滑動,當用戶執行其他的一些觸摸操作,比如接觸屏幕上的元素的時候。
兩個被常用的ViewConfiguration方法是getScaledMinimumFlingVelocity()和getScaledMaximumFlingVelocity()。這兩個方法返回最小和最大速度來發起一個fling,測量單位是像素每秒。

舉例:

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
    }
}

Extend a Child View's Touchable Area [擴展子視圖的可觸摸區域]

Android提供了TouchDelegate類,使得父View能夠擴展子View的觸摸區域。當一個子View所佔區域非常小,但是需要一個大的區域讓用戶觸摸操作時,這個是非常有用的。如果需要縮小子View的觸摸區域,也可以使用這種方法。

在下面的示例中,ImageButton就是"delegate view"(也就是需要父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>
下面的代碼片段做了以下一些事情:
1.獲取父view,並在UI線程中post一個Runnable。這確保了父view在調用getHitRect()方法之前列出了它的子視圖。getHitRect()方法在父視圖座標系中獲得子視圖的可點擊矩形框(可觸摸區域)。
2.找到ImageButton子view並調用getHitRect()來獲取子視圖的的可觸摸區域邊界。
3.擴展ImageButton的矩形邊界。
4.實例化一個TouchDelegate,並將擴充的可點擊矩形區域和ImageButton子視圖作爲傳遞參數。
5.在父view上面設置TouchDelegate,如此 在擴展區域上的觸摸動作會傳遞到子視圖。

在觸摸ImageButton的擴展可觸摸區域中,父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);
                }
            }
        });
    }
}


英文文檔地址:http://developer.android.com/training/gestures/viewgroup.html#vc

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章