Android自定义View实现拖动自动吸边效果
作者:Android师哥 发布时间:2021-11-18 03:00:38
标签:Android,拖动,吸边
本文实例为大家分享了Android自定义View实现拖动自动吸边的具体代码,供大家参考,具体内容如下
自定义View,一是为了满足设计需求,二是开发者进阶的标志之一。随心所欲就是我等奋斗的目标!!!
效果
实现逻辑
明确需求
1、实现控件跟随手指拖动
2、实现控件自动贴边
整理思路
1、既然要实现控件拖动,那么就离不开onTouchEvent()
这个方法,需要监听里面的按下和滑动事件。
2、 要实现自动贴边,需要监听onTouchEvent()
中手指离开屏幕事件。对于贴边的过程,我们用属性动画来解决。
3、事件的冲突问题也需要考虑,拖动、点击关系到了事件的拦截。
动手实现
在需求明确、思路清晰的情况下就要开始动手实现(需要了解自定义View的一些基础API),下面代码中注释写的基本都差不多,很好理解。欢迎指出讨论!!!
完整代码
Kotlin
class AttachButton: View {
private var mLastRawX: Float = 0F
private var mLastRawY: Float = 0F
private var isDrug = false
private var mRootMeasuredWidth = 0
private var mRootMeasuredHeight = 0
private var mRootTopY = 0
private var customIsAttach = false
private var customIsDrag = false
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
isClickable = true
initAttrs(context, attrs)
}
private fun initAttrs(context: Context, attrs: AttributeSet?) {
attrs?.let {
val mTypedAttay = context.obtainStyledAttributes(it, R.styleable.AttachButton)
customIsAttach =
mTypedAttay.getBoolean(R.styleable.AttachButton_customIsAttach, true)
customIsDrag =
mTypedAttay.getBoolean(R.styleable.AttachButton_customIsDrag, true)
mTypedAttay.recycle()
}
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
super.dispatchTouchEvent(event)
return true
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
event?.let {
//判断是否需要滑动
if (customIsDrag) {
//当前手指的坐标
val mRawX = it.rawX
val mRawY = it.rawY
when (it.action) {
MotionEvent.ACTION_DOWN -> {//手指按下
isDrug = false
//记录按下的位置
mLastRawX = mRawX
mLastRawY = mRawY
if (parent is ViewGroup) {
val mViewGroup = parent as ViewGroup
val location = IntArray(2)
mViewGroup.getLocationInWindow(location)
//获取父布局的高度
mRootMeasuredHeight = mViewGroup.measuredHeight
mRootMeasuredWidth = mViewGroup.measuredWidth
//获取父布局顶点的坐标
mRootTopY = location[1]
}
}
MotionEvent.ACTION_MOVE -> {//手指滑动
if (mRawX >= 0 && mRawX <= mRootMeasuredWidth && mRawY >= mRootTopY && mRawY <= (mRootMeasuredHeight + mRootTopY)) {
//手指X轴滑动距离
val differenceValueX: Float = mRawX - mLastRawX
//手指Y轴滑动距离
val differenceValueY: Float = mRawY - mLastRawY
//判断是否为拖动操作
if (!isDrug) {
isDrug =
sqrt(((differenceValueX * differenceValueX) + (differenceValueY * differenceValueY)).toDouble()) >= 2
}
//获取手指按下的距离与控件本身X轴的距离
val ownX = x
//获取手指按下的距离与控件本身Y轴的距离
val ownY = y
//理论中X轴拖动的距离
var endX: Float = ownX + differenceValueX
//理论中Y轴拖动的距离
var endY: Float = ownY + differenceValueY
//X轴可以拖动的最大距离
val maxX: Float = mRootMeasuredWidth - width.toFloat()
//Y轴可以拖动的最大距离
val maxY: Float = mRootMeasuredHeight - height.toFloat()
//X轴边界限制
endX = if (endX < 0) 0F else (if (endX > maxX) maxX else endX)
//Y轴边界限制
endY = if (endY < 0) 0F else (if (endY > maxY) maxY else endY)
//开始移动
x = endX
y = endY
//记录位置
mLastRawX = mRawX
mLastRawY = mRawY
}
}
MotionEvent.ACTION_UP -> {//手指离开
if (customIsAttach) {
//判断是否为点击事件
if (isDrug) {
val center = mRootMeasuredWidth / 2
//自动贴边
if (mLastRawX <= center) {
//向左贴边
animate()
.setInterpolator(BounceInterpolator())
.setDuration(500)
.x(0F)
.start()
} else {
//向右贴边
animate()
.setInterpolator(BounceInterpolator())
.setDuration(500)
.x(mRootMeasuredWidth - width.toFloat())
.start()
}
}
}
}
}
}
}
//是否拦截事件
return if (isDrug) isDrug else super.onTouchEvent(event)
}
}
Java
/**
* 自定义View实现拖动并自动吸边效果
* <p>
* 处理滑动和贴边 {@link #onTouchEvent(MotionEvent)}
* 处理事件分发 {@link #dispatchTouchEvent(MotionEvent)}
* </p>
*
* @attr customIsAttach //是否需要自动吸边
* @attr customIsDrag //是否可拖曳
*/
public class AttachButton extends View {
private float mLastRawX;
private float mLastRawY;
private final String TAG = "AttachButton";
private boolean isDrug = false;
private int mRootMeasuredWidth = 0;
private int mRootMeasuredHeight = 0;
private int mRootTopY = 0;
private boolean customIsAttach;
private boolean customIsDrag;
public AttachButton(Context context) {
this(context, null);
}
public AttachButton(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public AttachButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setClickable(true);
initAttrs(context, attrs);
}
/**
* 初始化自定义属性
*/
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray mTypedAttay = context.obtainStyledAttributes(attrs, R.styleable.AttachButton);
customIsAttach = mTypedAttay.getBoolean(R.styleable.AttachButton_customIsAttach, true);
customIsDrag = mTypedAttay.getBoolean(R.styleable.AttachButton_customIsDrag, true);
mTypedAttay.recycle();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
super.dispatchTouchEvent(event);
return true;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
//判断是否需要滑动
if (customIsDrag) {
//当前手指的坐标
float mRawX = ev.getRawX();
float mRawY = ev.getRawY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN://手指按下
isDrug = false;
//记录按下的位置
mLastRawX = mRawX;
mLastRawY = mRawY;
ViewGroup mViewGroup = (ViewGroup) getParent();
if (mViewGroup != null) {
int[] location = new int[2];
mViewGroup.getLocationInWindow(location);
//获取父布局的高度
mRootMeasuredHeight = mViewGroup.getMeasuredHeight();
mRootMeasuredWidth = mViewGroup.getMeasuredWidth();
//获取父布局顶点的坐标
mRootTopY = location[1];
}
break;
case MotionEvent.ACTION_MOVE://手指滑动
if (mRawX >= 0 && mRawX <= mRootMeasuredWidth && mRawY >= mRootTopY && mRawY <= (mRootMeasuredHeight + mRootTopY)) {
//手指X轴滑动距离
float differenceValueX = mRawX - mLastRawX;
//手指Y轴滑动距离
float differenceValueY = mRawY - mLastRawY;
//判断是否为拖动操作
if (!isDrug) {
if (Math.sqrt(differenceValueX * differenceValueX + differenceValueY * differenceValueY) < 2) {
isDrug = false;
} else {
isDrug = true;
}
}
//获取手指按下的距离与控件本身X轴的距离
float ownX = getX();
//获取手指按下的距离与控件本身Y轴的距离
float ownY = getY();
//理论中X轴拖动的距离
float endX = ownX + differenceValueX;
//理论中Y轴拖动的距离
float endY = ownY + differenceValueY;
//X轴可以拖动的最大距离
float maxX = mRootMeasuredWidth - getWidth();
//Y轴可以拖动的最大距离
float maxY = mRootMeasuredHeight - getHeight();
//X轴边界限制
endX = endX < 0 ? 0 : endX > maxX ? maxX : endX;
//Y轴边界限制
endY = endY < 0 ? 0 : endY > maxY ? maxY : endY;
//开始移动
setX(endX);
setY(endY);
//记录位置
mLastRawX = mRawX;
mLastRawY = mRawY;
}
break;
case MotionEvent.ACTION_UP://手指离开
//根据自定义属性判断是否需要贴边
if (customIsAttach) {
//判断是否为点击事件
if (isDrug) {
float center = mRootMeasuredWidth / 2;
//自动贴边
if (mLastRawX <= center) {
//向左贴边
AttachButton.this.animate()
.setInterpolator(new BounceInterpolator())
.setDuration(500)
.x(0)
.start();
} else {
//向右贴边
AttachButton.this.animate()
.setInterpolator(new BounceInterpolator())
.setDuration(500)
.x(mRootMeasuredWidth - getWidth())
.start();
}
}
}
break;
}
}
//是否拦截事件
return isDrug ? isDrug : super.onTouchEvent(ev);
}
}
自定义属性
<declare-styleable name="AttachButton">
<!--是否需要自动吸边-->
<attr name="customIsAttach" format="boolean" />
<!--是否可拖曳-->
<attr name="customIsDrag" format="boolean" />
</declare-styleable>
来源:https://blog.csdn.net/Common_it/article/details/89284887


猜你喜欢
- IntelliJ IDEA2022 springboot 热部署 html#pom.xml<dependency>
- 下文笔者讲述java中String.intern()方法的功能简介说明,如下所示:String.intern原理String.intern(
- 前言开发做得久了,总免不了会遇到各种坑。而在Android开发的路上,『软键盘挡住了输入框』这个坑,可谓是一个旷日持久的巨坑——来来来,我们
- 有时候数据库文档需要整理,可是只能手动的复制粘贴,心中一万只草泥马奔腾而过。。。screw简洁好用的数据库表结构文档生成工具。1. 创建项目
- Dialog的基本方法//创建DialogAlertDialog.Builder builder = new AlertDialog.Bui
- 在Web开发过程中离不开数据的交互,这就需要规定交互数据的相关格式,以便数据在客户端与服务器之间进行传递。数据的格式通常有2种:1、xml;
- 这篇文章主要介绍了SpringBoot项目没有把依赖的jar包一起打包的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一
- 在java的开发学习中,可能需要想了解class文件对应的代码内容是什么,如果我们使用IDE工具,可以通过IDE工具的各种反编译插件去进行反
- 随着市面上越来越多三方APP的出现,某些手机厂商也开始对这些APP进行了安装限制或者运行限制,或者三方APP自身的版本过低,无法被特定的系统
- 一、结论先行ArrayList在JDK1.8与JDK1.7底层区别JDK1.7:ArrayList像饿汉式,直接创建一个初始容量为10的数组
- PS:本文包含了大部分strings函数的说明,并附带举例说明。本来想自己整理一下的,发现已经有前辈整理过了,就转了过来。修改了原文一些源码
- C#字符串提取数值(带小数点)string input = "树2草45210.2m2";if (GetInputUti
- 文章开始之前,先看一下效果图,看是不是您正所需要的:一、构建计算器的界面要构建出一个好看点的计算器界面,还是需要颇费些小心思的,我做这个的时
- 教你如何用C#制作文字转换成声音程序在System.Speech命名空间下,SpeechSynthesizer类可以把文字读出来,一起来玩下
- 具体代码如下所示:***web.xml***<?xml version="1.0" encoding="
- 本文实例为大家分享了android九宫格可分页加载控件的具体实现代码,供大家参考,具体内容如下github地址基本思路是viewpager+
- 概述在实际项目开发中如果需要支持多语言,我们需要整理项目中所有的字符串并翻译成对应的语种放在相应的文件夹下,就像这样最让我们头痛的是我们得一
- 本文介绍了Spring @Async异步线程池用法总结,分享给大家,希望对大家有帮助1. TaskExecutorspring异步线程池的接
- yaml语法注解配置文件两种形式application.properties和.yaml第一种语法 key=value第二种key:空格va
- 本文实例讲述了Android编程实现画板功能的方法。分享给大家供大家参考,具体如下:Android实现画板主要有2种方式,一种是用自定义Vi