一:布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/re">
<activity.example.com.ballviewdemo.BallView
android:id="@+id/circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
二:自定义类继承view
package activity.example.com.ballviewdemo;
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;
import android.view.WindowManager;
/**
* Created by 壹颗大金星 on 2017/11/2.
*/
public class BallView extends View{
private int x = 100;
private int y = 100;
Context context;
public BallView(Context context) {
this(context,null);
this.context=context;
}
public BallView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
this.context=context;
}
public BallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context=context;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 画笔
Paint paint = new Paint();
//设置画笔颜色
paint.setColor(Color.RED);
//绘制圆
//cx :圆心的x坐标
//cy :圆心的y坐标
//radius :圆的半径
//paint :画笔
canvas.drawCircle(x, y, 50, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
// 获取当前触摸点的x,y坐标
x = (int) event.getX();
y = (int) event.getY();
break;
}
//获取屏幕宽高
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int width = manager.getDefaultDisplay().getWidth();
int heigh = manager.getDefaultDisplay().getHeight();
//重新绘制圆 ,控制小球不会被移出屏幕
if(x>=20 && y>=20 && x<=width-20 && y<=heigh-90){
this.invalidate();
}
// 自己处理触摸事件
return true;
}
}