ViewGroup에서 터치 이벤트 관리

단일 호출에서 터치 이벤트 처리 ViewGroup은(는) 특별한 주의를 기울입니다 ViewGroup에는 일반적으로 서로 다른 터치 이벤트를 ViewGroup 자체보다 훨씬 더 많이 사용합니다. 각 뷰가 이를 위한 터치 이벤트가 있으면 onInterceptTouchEvent() 메서드를 사용하여 축소하도록 요청합니다.

ViewGroup의 터치 이벤트 가로채기

onInterceptTouchEvent() 메서드는 터치 이벤트가 감지될 때마다 호출됩니다. 하위 요소의 표면을 포함하여 ViewGroup의 표면입니다. 만약 onInterceptTouchEvent()true을 반환합니다. <ph type="x-smartling-placeholder">MotionEvent</ph> 가로채기됩니다. 즉, 하위 요소가 아닌 onTouchEvent() 메서드를 호출합니다.

onInterceptTouchEvent() 메서드를 사용하면 상위 요소가 터치 이벤트를 볼 수 있습니다. 하위 요소가 그러기 전에 onInterceptTouchEvent()에서 true를 반환하는 경우 이전에 터치 이벤트를 처리했던 하위 뷰가 ACTION_CANCEL, 그 시점부터의 이벤트는 상위 요소의 onTouchEvent() 메서드로 전송됩니다. 평소 취급할 수 있습니다. onInterceptTouchEvent()false 및 이벤트가 뷰 계층 구조를 따라 일반적인 타겟으로 이동할 때 이벤트를 감시하고, 자체 onTouchEvent()가 있는 이벤트.

다음 스니펫에서 MyViewGroup 클래스는 ViewGroup를 확장합니다. MyViewGroup은 여러 하위 뷰를 포함하고 있습니다. 자녀 화면 모드를 손가락으로 드래그하는 경우 가로로 고정하면 하위 뷰는 더 이상 터치 이벤트를 받지 않고 MyViewGroup가 터치를 처리합니다. 할 수 있습니다. 그러나 하위 뷰에서 버튼을 누르거나 하위 뷰를 스크롤하면 하위 요소가 의도된 것이므로 상위 요소가 이러한 터치 이벤트를 가로채지 않습니다. 있습니다. 이 경우 onInterceptTouchEvent()false를 반환하고 MyViewGroup 클래스의 onTouchEvent()가 호출되지 않습니다.

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 only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can 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 // Don't intercept the touch event. Let the child handle it.
            }
            MotionEvent.ACTION_MOVE -> {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    true
                } else {

                    // If the user drags their finger horizontally more than the
                    // touch slop, start the scroll.

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

                    // Touch slop is calculated using ViewConfiguration constants.
                    if (xDiff > mTouchSlop) {
                        // Start scrolling!
                        mIsScrolling = true
                        true
                    } else {
                        false
                    }
                }
            }
            ...
            else -> {
                // In general, don't intercept touch events. The child view
                // handles them.
                false
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // Here, you actually handle the touch event. For example, if the action
        // is ACTION_MOVE, scroll this container. This method is only called if
        // the touch event is 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 only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can 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; // Don't intercept touch event. Let the child handle it.
        }

        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    return true;
                }

                // If the user drags their finger horizontally more than the
                // touch slop, start the scroll.

                // Left as an exercise for the reader.
                final int xDiff = calculateDistanceX(ev);

                // Touch slop is calculated using ViewConfiguration constants.
                if (xDiff > mTouchSlop) {
                    // Start scrolling.
                    mIsScrolling = true;
                    return true;
                }
                break;
            }
            ...
        }

        // In general, don't intercept touch events. The child view handles them.
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Here, you actually handle the touch event. For example, if the
        // action is ACTION_MOVE, scroll this container. This method is only
        // called if the touch event is intercepted in onInterceptTouchEvent.
        ...
    }
}

ViewGroup는 또한 requestDisallowInterceptTouchEvent() 메서드를 사용하여 축소하도록 요청합니다. ViewGroup는 하위 요소가 상위 요소와 그 상위 요소를 원하지 않을 때 이 메서드를 호출합니다. 상위에서 onInterceptTouchEvent()를 사용하여 터치 이벤트를 가로챕니다.

ACTION_OUTSIDE 이벤트 처리

ViewGroupMotionEvent을 수신하면 ACTION_OUTSIDE, 이 이벤트는 기본적으로 하위 요소에 전달되지 않습니다. 다음을 사용하여 MotionEvent를 처리하려면 ACTION_OUTSIDE, 다음 중 하나: <ph type="x-smartling-placeholder">dispatchTouchEvent(MotionEvent event)</ph> 적절한 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 occurs, do something.
    }
    return false
}
...
MotionEvent.ACTION_UP -> {
    ...
    if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) {
        // The criteria are 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 occurs, do something.
    }
...
case MotionEvent.ACTION_UP: {
    ...
    } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
            && velocityY < velocityX) {
        // The criteria are satisfied, do something.
    }
}

하위 뷰의 터치 가능한 영역 확장

Android는 TouchDelegate 클래스로 이동해야 합니다. 상위 요소가 하위 뷰의 경계 너머로 터치 가능 영역을 확장할 수 있어야 합니다. 이 은 하위 요소가 작지만 더 큰 터치 영역이 필요한 경우에 유용합니다. 또한 이 하위 요소의 터치 영역을 축소하는 접근 방식을 사용합니다.

다음 예에서 ImageButton은(는) _델리입니다. 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>

다음 스니펫은 이러한 작업을 완료합니다.

  • 상위 뷰를 가져오고 Runnable을 게시합니다. UI 스레드에 있을 수 있습니다. 이렇게 하면 상위 요소가 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, which is 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

            // Set the TouchDelegate on the parent view so 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 receives
                // motion events.
                touchDelegate = TouchDelegate(delegateArea, myButton)
            }
        }
    }
}

Java

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, which is 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 receives
                // motion events.
                TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
                        myButton);

                // Set the TouchDelegate on the parent view so that touches
                // within the touch delegate bounds are routed to the child.
                if (View.class.isInstance(myButton.getParent())) {
                    ((View) myButton.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }
}