ViewGroup
에서 터치 이벤트를 처리할 때는 특별히 주의해야 합니다. ViewGroup
에 ViewGroup
자체와 다른 터치 이벤트의 타겟인 하위 요소가 있는 것이 일반적이기 때문입니다. 각 뷰가 의도대로 올바르게 터치 이벤트를 수신하도록 하려면 onInterceptTouchEvent()
메서드를 재정의합니다.
다음 관련 리소스를 참고하세요.
ViewGroup의 터치 이벤트 가로채기
onInterceptTouchEvent()
메서드는 하위 요소의 표면을 비롯하여 ViewGroup
의 표면에서 터치 이벤트가 감지될 때마다 호출됩니다. onInterceptTouchEvent()
가 true
를 반환하면 MotionEvent
를 가로채게 됩니다. 즉, 하위 요소로 전달되지 않고 상위 요소의 onTouchEvent()
메서드에 전달됩니다.
onInterceptTouchEvent()
메서드를 사용하면 상위 요소가 하위 요소보다 먼저 터치 이벤트를 볼 수 있습니다. onInterceptTouchEvent()
에서 true
를 반환하면 이전에 터치 이벤트를 처리하던 하위 뷰가 ACTION_CANCEL
를 수신하고, 이 시점부터의 이벤트는 일반적인 처리를 위해 상위 요소의 onTouchEvent()
메서드로 전송됩니다. onInterceptTouchEvent()
는 뷰 계층 구조에서 자체 onTouchEvent()
로 이벤트를 처리하는 일반적인 타겟으로 이동할 때 false
를 반환하고 이벤트를 감시할 수도 있습니다.
다음 스니펫에서 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. ... } }
Java
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()
메서드도 제공합니다. 하위 요소가 상위 요소 및 그 상위 요소에서 onInterceptTouchEvent()
로 터치 이벤트를 가로채는 것을 원하지 않는 경우 ViewGroup
는 이 메서드를 호출합니다.
ACTION_OUTSIDE 이벤트 처리
ViewGroup
가 ACTION_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 occurs, do something. } return false } ... MotionEvent.ACTION_UP -> { ... if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) { // The criteria are satisfied, do something. } }
Java
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
는 _위임된 뷰_, 즉 상위 요소가 확장되는 터치 영역을 가진 하위 요소입니다. 레이아웃 파일은 다음과 같습니다.
<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, 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); } } }); } }