1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.wallpaper.picker 17 18 import android.content.Context 19 import android.util.AttributeSet 20 import android.view.MotionEvent 21 import android.view.ViewConfiguration 22 import androidx.core.widget.NestedScrollView 23 import kotlin.math.abs 24 25 /** 26 * This nested scroll view will detect horizontal touch movements and stop vertical scrolls when a 27 * horizontal touch movement is detected. 28 */ 29 class HorizontalTouchMovementAwareNestedScrollView(context: Context, attrs: AttributeSet?) : 30 NestedScrollView(context, attrs) { 31 32 private var startXPosition = 0f 33 private var startYPosition = 0f 34 private var isHorizontalTouchMovement = false 35 onInterceptTouchEventnull36 override fun onInterceptTouchEvent(event: MotionEvent): Boolean { 37 when (event.action) { 38 MotionEvent.ACTION_DOWN -> { 39 startXPosition = event.x 40 startYPosition = event.y 41 isHorizontalTouchMovement = false 42 } 43 MotionEvent.ACTION_MOVE -> { 44 val xMoveDistance = abs(event.x - startXPosition) 45 val yMoveDistance = abs(event.y - startYPosition) 46 if ( 47 !isHorizontalTouchMovement && 48 xMoveDistance > yMoveDistance && 49 xMoveDistance > ViewConfiguration.get(context).scaledTouchSlop 50 ) { 51 isHorizontalTouchMovement = true 52 } 53 } 54 else -> {} 55 } 56 return if (isHorizontalTouchMovement) { 57 // We only want to intercept the touch event when the touch moves more vertically than 58 // horizontally. So we return false. 59 false 60 } else { 61 super.onInterceptTouchEvent(event) 62 } 63 } 64 } 65