【Touch&input 】管理ViewGroup中的觸摸事件(9)

在a中處理觸摸事件ViewGroup需要格外小心,因爲一般情況下ViewGroup,讓孩子成爲不同於ViewGroup 本身的觸摸事件的目標。爲了確保每個視圖都能正確接收預定給它的觸摸事件,請覆蓋該onInterceptTouchEvent()方法。

請參閱以下相關資源:

攔截ViewGroup中的觸摸事件


onInterceptTouchEvent() 每當在ViewGroup包括其子表面上的表面上檢測到觸摸事件時調用該方法 。如果 onInterceptTouchEvent() 返回true,MotionEvent則被截獲,這意味着它不會傳遞給孩子,而是傳遞給onTouchEvent()父級的 方法。

該onInterceptTouchEvent() 方法讓父母有機會在其子女面前看到觸摸事件。如果您true從中 返回onInterceptTouchEvent(),之前處理觸摸事件的子視圖會收到一個ACTION_CANCEL,並且從該點開始的事件將發送到父級 onTouchEvent()方法以進行常規處理。 onInterceptTouchEvent()也可以返回false並簡單地監視事件,因爲它們沿着視圖層次傳遞到它們通常的目標,這些目標將自己處理事件 onTouchEvent()。

在下面的代碼片段中,這個類MyViewGroup擴展了 ViewGroup。 MyViewGroup包含多個子視圖。如果您將手指水平拖過子視圖,則子視圖不應再獲取觸摸事件,並且 MyViewGroup應該通過滾動其內容來處理觸摸事件。但是,如果按子視圖中的按鈕或垂直滾動​​子視圖,父級不應攔截這些觸摸事件,因爲子級是預定目標。在這種情況下, 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()方法。在ViewGroup調用此方法時,一個孩子不希望父母和祖先攔截觸摸事件與 onInterceptTouchEvent()。

處理ACTION_OUTSIDE事件

如果ViewGroup收到一個MotionEvent 帶有ACTION_OUTSIDE,該事件將不會默認派遣其子。要處理一個MotionEvent with ACTION_OUTSIDE,可以重寫 dispatchTouchEvent(MotionEvent event) 以分派給適當的View,或者在相關的Window.Callback(例如Activity)中處理它 。

使用ViewConfiguration常量


上面的代碼片段使用當前ViewConfiguration初始化一個變量調用mTouchSlop。您可以使用ViewConfiguration該類訪問Android系統使用的常見距離,速度和時間。

“觸摸斜率”是指在手勢被解釋爲滾動之前,用戶的觸摸可以漫遊的像素距離。觸摸坡度通常用於防止用戶在執行其他觸摸操作(例如觸摸屏幕元素)時發生意外滾動。

另外兩種常用的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
    }
}

延伸子視圖的可觸摸區域


Android提供了這個TouchDelegate類,使父母可以將子視圖的可觸摸區域擴展到孩子的範圍之外。當孩子必須很小時,這是很有用的,但是應該有一個更大的觸摸區域。如果需要,您也可以使用這種方法縮小孩子的觸摸區域。

在下面的示例中,an ImageButton是“委託視圖”(即父級將延伸的觸摸區域的子項)。這是佈局文件:

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

下面的代碼片段執行以下操作:

  • 獲取父視圖並Runnable在UI線程上發佈一個。這可確保父母在調用getHitRect()方法之前佈置子女。該getHitRect()方法在父級座標中獲取子級的命中矩形(可觸摸區域)。
  • 查找ImageButton子視圖並調用getHitRect()以獲取兒童可觸摸區域的邊界。
  • 擴展ImageButton命中矩形的邊界。
  • 實例化一個TouchDelegate傳入展開的命中矩形和ImageButton子視圖作爲參數。
  • TouchDelegate在父視圖上設置,使觸摸委託範圍內的觸摸路由到子項

作爲ImageButton子視圖的觸摸委託,父視圖將接收所有觸摸事件。如果觸摸事件發生在孩子的命中矩形內,父母會將觸摸事件傳遞給孩子進行處理。

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);
                }
            }
        });
    }
}
Lastest Update:2018.04.25

聯繫我

QQ:94297366
微信打賞:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

公衆號推薦:

【Touch&input 】管理ViewGroup中的觸摸事件(9)

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