欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

跟随手指的小球

程序员文章站 2022-06-09 10:28:10
...
package com.example.shangqiuju.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

/**
 * 自定义组件
 * Created by shangqiuju on 2021/7/30.
 */

public class DrawView extends View{
    public float currentX = 40;
    public float currentY = 50;

    /**
     *
     * @param context
     */
    public DrawView(Context context){
        super(context);
        //TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //创建画笔
        Paint p = new Paint();
        //设置画笔的颜色
        p.setColor(7777777);
        //绘制一个画图(作为小球)
        canvas.drawCircle(currentX,currentY,15,p);
    }
}

首先自定义控件DrawView

然后为程序绑定一个OnTouchListener的监听,手指在触摸屏上移动,将不断触发摸屏事件

事件监听中负责的坐标将被传入DrawView组件,并通知该组件重绘

package com.example.shangqiuju.myapplication;

import android.app.Application;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * Created by shangqiuju on 2021/7/30.
 */

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        //获取局部文件中的LinearLayout容器
        LinearLayout root = (LinearLayout) findViewById(R.id.rot);
        //创建DrawView组件
        final DrawView draw = new DrawView(this);
        //设置自定义组件的最大宽度、高度
        draw.setMinimumWidth(300);
        draw.setMinimumHeight(500);
        //为draw组件绑定Touch事件
        draw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                //修改draw组件的currentX,currentY两个属性
                draw.currentX = motionEvent.getX();
                draw.currentY = motionEvent.getY();
                //通知draw组织重绘
                draw.invalidate();
                //返回true表明处理方法已经处理该事件
                return false;
            }
        });
        root.addView(draw);
    }
}