/**
* @创建者 yindj
* @创建时间 2018/4/20 9:38
* @技术交流 (QQ:429310921)
* @部门 天元陆兵研发部
* @描述 实现基本功能
*/
/**自定义一个CustomView继承自View*/
public class CustomView extends View {
private int lastX;
private int lastY;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//获取手指触摸点的横坐标和纵坐标
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
/*计算偏移的距离*/
int offsetX = x - lastX;
int offsetY = y - lastY;
/*调用layout方法重新放置它的位置*/
layout(getLeft()+offsetX,getTop()+offsetY,
getRight()+offsetX,getBottom()+offsetY);
break;
}
return true;
}
}
接下来在布局中引入刚才创建的自定义CustomView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.auicyh.android_view.MainActivity">
<view.CustomView
android:layout_width="80dp"
android:layout_height="80dp"
android:background="@android:color/holo_red_light"/>
</LinearLayout>
可以用手指触摸它了。