自定义布局
<example.view.BallsView
android :layout_width= "match_parent"
android :layout_height= "match_parent" />
//自定义类
public class BallsView extends View {
private int height ;
private int width ;
private int x ;
private int y ;
private int downx ;
private int downy ;
private boolean onBall ;
//这三个方法是你做初始化的业务逻辑
//在代码值使用自定义控件(new BallsView)自动回调此方法
public BallsView (Context context) {
super (context);
}
//XML布局值用此自定义控件,自动回调此方法
public BallsView (Context context, AttributeSet attrs) {
super (context, attrs);
}
//XML布局中使用此自定义控件,且带有有样式时,自动回调
public BallsView (Context context, AttributeSet attrs, int defStyleAttr) {
super (context, attrs, defStyleAttr);
intiView();
}
//设置圆半径的距离
private int banjiu = 50 ;
//做一些自定义控件初始化的操作
private void intiView () {
}
//进行测量
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super .onMeasure(widthMeasureSpec, heightMeasureSpec);
//獲取當前控件的寬和高
height = this .getHeight();
width = this .getWidth();
//獲取屏幕的正中心點
x = height / 2 ;
y = width / 2 ;
}
//此方法进行绘制
@Override
protected void onDraw (Canvas canvas) {
super .onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.GREEN );
//画圆,根据他需要什么参数(ctr+q),我就参加sm参数
canvas.drawCircle(x , y , banjiu , paint);
}
@Override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN ://按下时,回调
//进行判断,用户的手是否在圆上
downx = (int ) event.getX();
downy = (int ) event.getY();
onBall = isOnBall(downx , downy );
Toast.makeText (getContext(), "是否用户的手点击到圆了么" , Toast.LENGTH_LONG ).show();
break;
case MotionEvent.ACTION_MOVE ://移动时,回调
//判断用户的手是否在圆上,在圆上的话就让代码时时移动。
if (onBall ) {
x = (int ) event.getX();
y = (int ) event.getY();
}
postInvalidate();
break;
case MotionEvent.ACTION_UP ://松开时回调
break;
}
return true;
}
//java,对象,方法,参数,结果,当遇到一个不知道的方法只要知道传什么,返回什么。
//算法和封装。
//作为一个程序员必须要有的能力:1.解决问题的能力2.自学能力3.表达能力
private boolean isOnBall (int downx, int downy) {
//勾股定理,得到按下的半徑
double sqrt = Math.sqrt ((downx - x ) * (downx - x ) + (downy - y ) * (downy - y ));
//對應圓半徑和按下半徑進行判斷,看用戶的手是否在圓心上
if (sqrt <= banjiu ) {
return true;
}
return false;
}
}