本文主要是介绍可拖动的组件,可更改为其它View,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
可拖动的组件,可更改为其它View
效果图
自定义View源码
DragTextView
package com.demo.drag;import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.RelativeLayout;/*** Created by talon on 2020/5/21* note: 可拖动的View,这里是TextView,可以换成其他的View* 解决了更新视图时,该View坐标会重置的问题*/
public class DragTextView extends android.support.v7.widget.AppCompatTextView {private final String TAG = "MyDragTextView";private int mLastX;private int mLastY;RelativeLayout.LayoutParams params;public DragTextView(Context context) {super(context);}public DragTextView(Context context, AttributeSet attrs) {super(context, attrs);}public DragTextView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overridepublic boolean onTouchEvent(MotionEvent event) {int parentWidth = ((ViewGroup) getParent()).getWidth();int parentHeight = ((ViewGroup) getParent()).getHeight();int x = (int) event.getRawX();int y = (int) event.getRawY();// 注意:xx.LayoutParams这里的xx应该是该组件的父布局类型// 注意:这句话必须在该组件已经添加到父布局中才会起作用,所以这句话我没有写在构造函数中,而是写在这里params = (RelativeLayout.LayoutParams) this.getLayoutParams();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:mLastX = x;mLastY = y;break;case MotionEvent.ACTION_MOVE:int offSetX = x - mLastX;int offSetY = y - mLastY;// 限制边界。int left = getLeft() + offSetX;if (left<0)left = 0;if (left>(parentWidth-getWidth()))left = parentWidth-getWidth();int top = getTop() + offSetY;if (top<0)top = 0;if (top>(parentHeight-getHeight()))top= parentHeight-getHeight();int right = getRight() + offSetX;if (right<getWidth())right = getWidth();if (right>parentWidth)right = parentWidth;int bottom = getBottom() + offSetY;if (bottom<getHeight())bottom = getHeight();if (bottom>parentHeight)bottom = parentHeight;// LogWrapper.e(TAG,"left:"+left+"_top:"+top+"_right:"+right+"_bottom:"+bottom);// 1.(不限制滑动范围)调用layout方法来重新放置它的位置
// layout(getLeft() + offSetX, getTop() + offSetY, getRight() + offSetX, getBottom() + offSetY);// 2. (限制滑动范围)layout(left, top, right, bottom);mLastX = x;mLastY = y;break;case MotionEvent.ACTION_UP:
// int screenWidth = ScreenUtils.getScreenWidth(getContext());
// int screenHeight = ScreenUtils.getScreenHeight(getContext());// 左上右下 的 margin,后面两个参数必须要设置,不然在边界处可能会引起图片的变形params.setMargins(getLeft(), getTop(), parentWidth - (getLeft() + getWidth()), parentHeight - (getTop() + getHeight()));setLayoutParams(params);break;default:break;}return true;}
}
demo地址
https://download.csdn.net/download/u011368551/12453968
这篇关于可拖动的组件,可更改为其它View的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!