ViewGroup에서 터치 이벤트 관리

ViewGroup에서 터치 이벤트를 처리할 때는 특별히 주의해야 합니다. 왜냐하면 ViewGroup에는 ViewGroup과 다른 터치 이벤트의 타겟인 하위 요소가 있는 경우가 흔하기 때문입니다. 각 뷰가 의도대로 올바르게 터치 이벤트를 수신하도록 하려면 onInterceptTouchEvent() 메서드를 재정의합니다.

다음 관련 리소스를 참조하세요.

ViewGroup의 터치 이벤트 가로채기

onInterceptTouchEvent() 메서드는 ViewGroup 표면(하위 요소의 표면 포함)에서 터치 이벤트가 감지될 때마다 호출됩니다. onInterceptTouchEvent()true를 반환하면 MotionEvent가 가로채기되며, 이는 하위 요소로 전달되지 않고 상위 요소의 onTouchEvent() 메서드에 전달됨을 의미합니다.

onInterceptTouchEvent() 메서드는 상위 요소가 하위 요소보다 먼저 터치 이벤트를 확인할 기회를 제공합니다. onInterceptTouchEvent()에서 true를 반환하면 이전에 터치 이벤트를 처리하던 하위 뷰가 ACTION_CANCEL을 수신하고 이 시점 이후로는 이벤트가 상위 요소의 onTouchEvent() 메서드로 전송되어 일반적인 처리가 이루어집니다. 또한 onInterceptTouchEvent()false를 반환하고 이벤트가 뷰 계층 구조 아래로 이동해 일반적인 타겟에 도달하고 이 타겟에서 고유한 onTouchEvent()로 이벤트를 처리하는 것을 감시하기만 할 수도 있습니다.

다음 스니펫에서 MyViewGroup 클래스는 ViewGroup을 확장합니다. MyViewGroup은 여러 하위 뷰를 포함하고 있습니다. 하위 뷰를 손가락으로 가로로 드래그하면 하위 뷰는 더 이상 터치 이벤트를 받지 않아야 하며 MyViewGroup이 콘텐츠를 스크롤하여 터치 이벤트를 처리해야 합니다. 하지만 하위 뷰에서 버튼을 누르거나 하위 뷰를 세로로 스크롤하면 의도하는 타겟이 하위 뷰이기 때문에 상위 요소가 이 터치 이벤트를 가로채서는 안 됩니다. 이런 경우 onInterceptTouchEvent()false를 반환해야 하며 MyViewGrouponTouchEvent()는 호출되지 않습니다.

Kotlin

    class MyViewGroup @JvmOverloads constructor(
            context: Context,
            private val mTouchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop
    ) : ViewGroup(context) {

        ...

        override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
            /*
             * 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.
             */
            return when (ev.actionMasked) {
                // Always handle the case of the touch gesture being complete.
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    // Release the scroll.
                    mIsScrolling = false
                    false // Do not intercept touch event, let the child handle it
                }
                MotionEvent.ACTION_MOVE -> {
                    if (mIsScrolling) {
                        // We're currently scrolling, so yes, intercept the
                        // touch event!
                        true
                    } else {

                        // If the user has dragged her finger horizontally more than
                        // the touch slop, start the scroll

                        // left as an exercise for the reader
                        val xDiff: Int = calculateDistanceX(ev)

                        // Touch slop should be calculated using ViewConfiguration
                        // constants.
                        if (xDiff > mTouchSlop) {
                            // Start scrolling!
                            mIsScrolling = true
                            true
                        } else {
                            false
                        }
                    }
                }
                ...
                else -> {
                    // In general, we don't want to intercept touch events. They should be
                    // handled by the child view.
                    false
                }
            }
        }

        override fun onTouchEvent(event: MotionEvent): Boolean {
            // 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
            ...
        }
    }
    

자바

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

ViewGrouprequestDisallowInterceptTouchEvent() 메서드도 제공합니다. 하위 요소가 직속 상위 및 전체 상위 요소에서 onInterceptTouchEvent()로 터치 이벤트를 가로채는 것을 원하지 않을 때 ViewGroup은 이 메서드를 호출합니다.

ACTION_OUTSIDE 이벤트 처리

ViewGroupACTION_OUTSIDE가 포함된 MotionEvent를 수신하면 이 이벤트는 기본적으로 하위 요소에 전달되지 않습니다. ACTION_OUTSIDE가 포함된 MotionEvent를 처리하려면 dispatchTouchEvent(MotionEvent event)를 재정의하여 적절한 View에 전달하거나 관련 Window.Callback(예: Activity)에서 처리합니다.

ViewConfiguration 상수 사용

위의 스니펫은 현재 ViewConfiguration을 사용하여 mTouchSlop이라는 변수를 초기화합니다. ViewConfiguration 클래스를 사용하면 Android 시스템에 사용되는 일반 거리, 속도 및 시간에 액세스할 수 있습니다.

'터치 슬롭'은 사용자의 터치 동작이 스크롤로 해석되기 전까지 배회할 수 있는 거리(픽셀 단위)를 말합니다. 터치 슬롭은 사용자가 화면상의 요소를 터치하는 등 다른 터치 작업을 할 때 실수로 스크롤되는 것을 방지하는 데 일반적으로 사용됩니다.

일반적으로 사용되는 두 가지의 다른 ViewConfiguration 메서드는 getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity()입니다. 이러한 메서드는 각각 살짝 튕기기를 시작하는 최저 속도와 최대 속도(단위: 초당 픽셀 수)를 반환합니다. 예를 들면 다음과 같습니다.

Kotlin

    private val vc: ViewConfiguration = ViewConfiguration.get(context)
    private val mSlop: Int = vc.scaledTouchSlop
    private val mMinFlingVelocity: Int = vc.scaledMinimumFlingVelocity
    private val mMaxFlingVelocity: Int = vc.scaledMaximumFlingVelocity

    ...

    MotionEvent.ACTION_MOVE -> {
        ...
        val deltaX: Float = motionEvent.rawX - mDownX
        if (Math.abs(deltaX) > mSlop) {
            // A swipe occurred, do something
        }
        return false
    }

    ...

    MotionEvent.ACTION_UP -> {
        ...
        if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) {
            // The criteria have been satisfied, do something
        }
    }
    

자바

    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 클래스를 제공합니다. 이 클래스는 하위 요소 자체는 작지만 하위 요소의 터치 영역은 커야 하는 경우에 유용합니다. 필요에 따라 하위 요소의 터치 영역을 축소하는 데도 이 접근 방식을 사용할 수 있습니다.

다음 예에서 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>
    

아래 스니펫에서는 다음을 처리합니다.

  • 상위 뷰를 가져오고 UI 스레드에 Runnable을 게시합니다. 이렇게 하면 상위 요소가 getHitRect() 메서드를 호출하기 전에 하위 요소를 레이아웃합니다. getHitRect() 메서드는 상위 요소의 좌표에서 하위 요소의 적중 사각형(터치 가능한 영역)을 가져옵니다.
  • ImageButton 하위 뷰를 찾고 getHitRect()를 호출하여 하위 요소의 터치 가능한 영역의 경계를 가져옵니다.
  • ImageButton의 적중 사각형 경계를 확장합니다.
  • TouchDelegate를 인스턴스화하여 확장된 적중 사각형 및 ImageButton 하위 뷰를 매개변수로 전달합니다.
  • 터치 위임의 경계 내부를 터치한 동작이 하위 요소에 라우팅되도록 상위 뷰에서 TouchDelegate를 설정합니다.

상위 뷰는 ImageButton 하위 뷰의 터치 위임 자격으로 모든 터치 이벤트를 수신합니다. 터치 이벤트가 하위 요소의 적중 사각형 내에서 발생했다면 상위 요소는 터치 이벤트를 처리하도록 하위 요소에 전달합니다.

Kotlin

    public class MainActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            // Post in the parent's message queue to make sure the parent
            // lays out its children before you call getHitRect()
            findViewById<View>(R.id.parent_layout).post {
                // The bounds for the delegate view (an ImageButton
                // in this example)
                val delegateArea = Rect()
                val myButton = findViewById<ImageButton>(R.id.button).apply {
                    isEnabled = true
                    setOnClickListener {
                        Toast.makeText(
                                this@MainActivity,
                                "Touch occurred within ImageButton touch region.",
                                Toast.LENGTH_SHORT
                        ).show()
                    }

                    // The hit rectangle for the ImageButton
                    getHitRect(delegateArea)
                }

                // Extend the touch area of the ImageButton beyond its bounds
                // on the right and bottom.
                delegateArea.right += 100
                delegateArea.bottom += 100

                // Sets the TouchDelegate on the parent view, such that touches
                // within the touch delegate bounds are routed to the child.
                (myButton.parent as? View)?.apply {
                    // 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(delegateArea, myButton)
                }
            }
        }
    }
    

자바

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