自定义View实现跟随手指的小球

package com.pingyijinren.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Administrator on 2016/5/21 0021.
 */
public class DrawView extends View {
    private float x=100;
    private float y=100;
    public DrawView(Context context){
        super(context);
    }   //自定义View时,必须实现View的三个构造函数

    public DrawView(Context context, AttributeSet attrs){
        super(context,attrs);
    }

    public DrawView(Context context, AttributeSet attrs, int defStyle){
        super(context,attrs,defStyle);
    }

    @Override
    public void onDraw(Canvas canvas){  //onDraw不是必需的,按需重写即可
        super.onDraw(canvas);
        Paint paint=new Paint();
        paint.setColor(Color.RED);
        canvas.drawCircle(x,y,100,paint);
    }

    public void setX(float x){
        this.x=x;
    }

    public void setY(float y){
        this.y=y;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pingyijinren.test.MainActivity">

    <com.pingyijinren.test.DrawView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/drawView"/>
</RelativeLayout>
package com.pingyijinren.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private DrawView drawView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            setContentView(R.layout.activity_main);
        }
        catch(Exception e){
            e.printStackTrace();
            Log.d("MainActivity",e.getMessage());
        }

        drawView=(DrawView)findViewById(R.id.drawView);
        drawView.setOnTouchListener(new View.OnTouchListener() {    //drawView响应屏幕触摸事件
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                drawView.setX(event.getX());
                drawView.setY(event.getY());
                drawView.invalidate();
                return true;
            }
        });
    }
}

 

转载于:https://www.cnblogs.com/zqxLonely/p/5514389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值