布局
<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"
android:orientation="vertical"
tools:context="com.bawey.mycerlier.MainActivity">
<com.bawey.mycerlier.view.Mycirlir
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
自定义view
package com.bawey.mycerlier.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by zld on 2018/2/24.
*/
public class Mycirlir extends View {
private Paint paint;
private int lastX;
private int lastY;
public Mycirlir(Context context) {
this(context,null);
}
public Mycirlir(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public Mycirlir(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿
paint.setColor(Color.RED);
paint.setStrokeWidth(3);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(100,100,100,paint);
super.onDraw(canvas);
}
//拖动事件
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
//得到间距
int mX= (int) event.getRawX();
int jX= mX- lastX;
int mY= (int) event.getRawY();
int jY= mY-lastY;
//得到原始上下左右坐标
int l = getLeft();
int r = getRight();
int t = getTop();
int b = getBottom();
//得到移动后的坐标;
l = l+jX;
r = r+jX;
t = t+jY;
b = b+jY;
//判断不超出屏幕
if(l<0){
l=0;
r=getWidth();
}
if(r<0){
r=0;
l=getWidth();
}
if(t<0){
t=0;
b=getWidth();
}
if(b<0){
b=0;
t=getWidth();
}
//显示赋值的位置
layout(l,t,r,b);
lastX=mX;
lastY = mY;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;//代表自己消耗事件
}
}
展示出来就ok了不需要添加权限