跟随手指的小球(实现代码)

一、创建DrawView类

public class DrawView extends View {
    public float currentX = 40 ;
    public float currentY = 50 ;
    //定义并创建画笔
    Paint p = new Paint();

    public DrawView(Context context) {
        super(context);
    }

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //创建画笔颜色
        p.setColor(Color.RED);
        //绘制一个小圆(作为小球)
        canvas.drawCircle(currentX,currentY,15,p);
    }
    //为该组件的触碰事件重写事件处理方法

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //修改currentX,currentY两个属性
        currentX = event.getX();
        currentY = event.getY();
        //通知当前组件绘制自己
        invalidate();
        //返回ture表名该处理方法已经处理该事件
        return true;
    }
}

二、在Activity里:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取布局文件中的LinearLayout容器
        LinearLayout root = findViewById(R.id.root);
        //创建DrawView组件
        DrawView drawView = new DrawView(this);
        //设置自定义组建的最小宽度、高度
        drawView.setMinimumWidth(0);
        drawView.setMinimumHeight(0);
        root.addView(drawView);
    }
}

三、给LinearLayout设置ID:

 android:id="@+id/root"

 

你可能感兴趣的:(跟随手指的小球(实现代码))