本文为博主原创--欢迎转载--但是请注明出处(珍惜他人劳动成果)!
本文实现的效果为图片(或者别的控件)跟随手指的滑动,不会超过屏幕边界,下面直接上代码,为什么代码报红我也不清楚哈,第一次写博客.
布局--
<?xml version="1.0" encoding="utf-8"?> <com.dingying.servicetest.MyView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@mipmap/ic_launcher"/> </com.dingying.servicetest.MyView>
1,自定义View继承ViewGroup,构造方法就选两个参数(XML使用)的就可以了
public class MyView extends ViewGroup { private TextView mTv; private int mChildWidthSize; private int mChildHeightSize; private int mLeft; private int mTop; private int mWidthSize; private int mHeightSize; public MyView(Context context, AttributeSet attrs) { super(context, attrs); }2,重写onLayout方法,因为继承的是ViewGroup
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { }3,重写onMeasure方法,测量出子控件和屏幕的大小
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 获取子控件 mTv = (TextView) getChildAt(0); // 测量子控件的声明 measureChildren(widthMeasureSpec,heightMeasureSpec); // 获取子控件的大小 mChildWidthSize = mTv.getMeasuredWidth(); mChildHeightSize = mTv.getMeasuredHeight(); // 获取屏幕的大小(本身) mWidthSize = MeasureSpec.getSize(widthMeasureSpec); mHeightSize = MeasureSpec.getSize(heightMeasureSpec); // 设置控件大小 setMeasuredDimension(mWidthSize, mHeightSize); }4,重写onTouchEvent方法
@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 获取点击的坐标,当点击坐标不在控件上面时,不触发后面的事件 int startX = (int) event.getX(); int startY = (int) event.getY(); Rect rect = new Rect(mLeft,mTop,mLeft+mChildWidthSize,mTop+mChildHeightSize); if(!(rect.contains(startX,startY))) { return false; } break; case MotionEvent.ACTION_MOVE: // 获取移动的坐标 float endX = event.getX(); float endY = event.getY(); // 移动后左边和顶边的坐标 mLeft = (int) (endX - mChildWidthSize/2); mTop = (int) (endY - mChildHeightSize /2); break; case MotionEvent.ACTION_UP: break; } // 刷新布局,也就是重新执行onLayout方法 requestLayout(); // 必须返回true,只有返回true的时候move和up事件才能执行 return true; }5,在onlayout方法中判断是否超出屏幕和子控件的布局
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if(mLeft < 0) { mLeft = 0; } if(mTop < 0) { mTop = 0; } if(mLeft+mChildWidthSize > mWidthSize) { mLeft = mWidthSize - mChildWidthSize; } if(mTop+mChildHeightSize > mHeightSize) { mTop = mHeightSize- mChildHeightSize; } mTv.layout(mLeft,mTop,mLeft+mChildWidthSize,mTop+mChildHeightSize); }这样就大功告成了!---如果对你有帮忙,请记得点赞哦--哈哈!