Last active
August 10, 2021 08:03
-
-
Save o0o0oo00/c1e597498c9079ee5ad16c5843975abf to your computer and use it in GitHub Desktop.
事件分发的精髓无外乎于此,写一个右滑消失的ViewGroup,不影响子view的事件接收
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.util.AttributeSet | |
import android.view.MotionEvent | |
import android.widget.FrameLayout | |
/** | |
* @author: zhaochunyu | |
* @description: 滑动消失ViewGroup | |
* @date: 2019-06-25 | |
*/ | |
class SwipeDismissLayout : FrameLayout { | |
constructor(context: Context?) : super(context) | |
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) | |
private var downX = 0F | |
private var distance = 0F | |
override fun dispatchTouchEvent(event: MotionEvent): Boolean { | |
when (event.action) { | |
MotionEvent.ACTION_DOWN -> { | |
distance = 0F | |
downX = event.rawX | |
} | |
MotionEvent.ACTION_MOVE -> { | |
distance = event.rawX - downX | |
if (distance > 60) { | |
translationX = distance | |
} | |
} | |
MotionEvent.ACTION_UP -> { | |
distance = event.rawX - downX | |
if (distance < width / 2) { | |
translationX = 0F | |
} | |
if (distance > width / 2) { | |
translationX = width.toFloat() | |
listener?.invoke() | |
} | |
} | |
} | |
// 滑动时候不要把事件传递给子view | |
return if (distance > 60) { | |
true | |
} else { | |
super.dispatchTouchEvent(event) | |
} | |
} | |
private var listener: (() -> Unit)? = null | |
fun setDismissListener(l: () -> Unit) { | |
listener = l | |
} | |
// 消费事件,不被父布局接收,如果SwipeDismissLayout及其子view没有设置点击事件,那么点击其内容事件会直接传递到SwipeDismissLayout的父布局 | |
override fun onTouchEvent(event: MotionEvent?): Boolean { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment