Android 管理ViewGroup中的觸摸事件

2018-08-02 18:21 更新

編寫:Andrwyw - 原文:http://developer.android.com/training/gestures/viewgroup.html

因?yàn)楹芏鄷r(shí)候是用ViewGroup的子類來(lái)做不同觸摸事件的目標(biāo),而不是ViewGroup本身,所以處理ViewGroup中的觸摸事件需要特別注意。 為了確保每個(gè)view能正確地接收到它們想要的觸摸事件,可以重寫onInterceptTouchEvent()函數(shù)。

在ViewGroup中截獲觸摸事件

每當(dāng)在ViewGroup(包括它的子View)的表面上檢測(cè)到一個(gè)觸摸事件,onInterceptTouchEvent()都會(huì)被調(diào)用。如果onInterceptTouchEvent()返回true,MotionEvent就被截獲了,這表示它不會(huì)被傳遞給其子View,而是傳遞給該父view自身的onTouchEvent()方法。

onInterceptTouchEvent()方法讓父view能夠在它的子view之前處理觸摸事件。如果我們讓onInterceptTouchEvent()返回true,則之前處理觸摸事件的子view會(huì)收到ACTION_CANCEL事件,并且該點(diǎn)之后的事件會(huì)被發(fā)送給該父view自身的onTouchEvent()函數(shù),進(jìn)行常規(guī)處理。onInterceptTouchEvent()也可以返回false,這樣事件沿view層級(jí)分發(fā)到目標(biāo)前,父view可以簡(jiǎn)單地觀察該事件。這里的目標(biāo)是指,通過(guò)onTouchEvent()處理消息事件的view。

接下來(lái)的代碼段中,MyViewGroup繼承自ViewGroupMyViewGroup有多個(gè)子view。如果我們?cè)谀硞€(gè)子View上水平地拖動(dòng)手指,該子view不會(huì)接收到觸摸事件,而是應(yīng)該由MyViewGroup處理這些觸摸事件來(lái)滾動(dòng)它的內(nèi)容。然而,如果我們點(diǎn)擊子view中的button,或垂直地滾動(dòng)子view,則父view不會(huì)截獲這些觸摸事件,因?yàn)樽觱iew本身就是預(yù)定目標(biāo)。在這些情況下,onInterceptTouchEvent()應(yīng)該返回false,MyViewGrouponTouchEvent()也不會(huì)被調(diào)用。

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()方法。當(dāng)子view不想該父view和祖先view通過(guò)onInterceptTouchEvent()截獲它的觸摸事件時(shí),可調(diào)用ViewGroup的該方法。

使用ViewConfiguration的常量

上面的代碼段中使用了當(dāng)前的ViewConfiguration來(lái)初始化mTouchSlop變量。我們可以使用ViewConfiguration類來(lái)獲取Android系統(tǒng)常用的一些距離、速度、時(shí)間值。

“Touch slop”是指在被識(shí)別為移動(dòng)的手勢(shì)前,用戶觸摸可移動(dòng)的那一段像素距離。Touch slop通常用來(lái)預(yù)防用戶在做一些其他觸摸操作時(shí),出現(xiàn)意外地滑動(dòng),例如觸摸屏幕上的組件。

另外兩個(gè)常用的ViewConfiguration函數(shù)是getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity()。這兩個(gè)函數(shù)會(huì)返回初始化一個(gè)快速滑動(dòng)(fling)的最小、最大速度(分別地),以像素每秒為測(cè)量單位。如:

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

擴(kuò)展子view的可觸摸區(qū)域

Android提供了TouchDelegate類,讓父view擴(kuò)展超出子view自身邊界的可觸摸區(qū)域。這在當(dāng)子view很小,但需要一個(gè)更大的觸摸區(qū)域時(shí)非常有用。如果需要,我們也可以使用這種方式來(lái)實(shí)現(xiàn)對(duì)子view的觸摸區(qū)域的收縮。

在下面的例子中,ImageButton對(duì)象是所謂的"delegate view"(是指觸摸區(qū)域?qū)⒈桓竩iew擴(kuò)展的那個(gè)子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對(duì)象并發(fā)送一個(gè)Runnable到UI線程。這會(huì)確保父view在調(diào)用getHitRect()函數(shù)前會(huì)布局它的子view。getHitRect()函數(shù)會(huì)獲得子view在父view坐標(biāo)系中的點(diǎn)擊矩形(觸摸區(qū)域)。
  • 找到ImageButton子view,然后調(diào)用getHitRect()來(lái)獲得它的觸摸區(qū)域的邊界。
  • 擴(kuò)展ImageButton的點(diǎn)擊矩形的邊界。
  • 實(shí)例化一個(gè)TouchDelegate對(duì)象,并把擴(kuò)展過(guò)的點(diǎn)擊矩形和ImageButton子view作為參數(shù)傳遞給它。
  • 設(shè)置父view的TouchDelegate,這樣在touch delegate邊界內(nèi)的點(diǎn)擊就會(huì)傳遞到該子view上。

ImageButton子view的touch delegate范圍內(nèi),父view會(huì)接收到所有的觸摸事件。如果觸摸事件發(fā)生在子view自身的點(diǎn)擊矩形中,父view會(huì)把觸摸事件交給子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);
                }
            }
        });
    }
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)