//布局怡然是自定义布局
MainActivity中还是什么都没有
下面是自定义类的代码

/**
 * date:2018/11/2
 * author:王加辉(家辉辉辉)
 * function:自绘式小球控件
 */
public class globlue extends View {

    private Paint mPaint;
    private int x;
    private int y;
    private int startX;
    private int startY;
    private boolean mBall;



    public globlue(Context context) {
        this(context,null);
    }

    public globlue(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public globlue(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化
        initView();


    }

    private void initView() {
        //创建画笔
        mPaint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = this.getWidth();
        int height = this.getHeight();

        x = width / 2 ;
        y = height/ 2 ;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    private static final  int RADIUS = 50 ;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制小圆
        mPaint.setColor(Color.BLUE);
        canvas.drawCircle(x,y,RADIUS,mPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:

                startX = (int) event.getX();
                startY = (int) event.getY();

                //判断当前点击的坐标是否在小球内部
                mBall = isBall(startX, startY);

                //toast在类中应该传什么上下文
                //Toast.makeText(context, "当前是否点击了小球"+mBall, Toast.LENGTH_SHORT).show();

                break;
                case MotionEvent.ACTION_MOVE:

                    if(mBall){
                        x = (int) event.getX();
                        y = (int) event.getY();
                        postInvalidate();
                    }



                    break;
            case MotionEvent.ACTION_UP:

                break;
        }


        return true;
    }

    //判断小球的位置
    private boolean isBall(int startX, int startY) {

        //求出小球的斜线
        double sqrt = Math.sqrt((startX - x) * (startX - x) + (startY - y) * (startY - y));

        //判断半径是否大于它
        if(sqrt<RADIUS){
            return true ;
        }

        return false;
    }
}
11-07 04:00