源码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.test6.TestView
android:id="@+id/testview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
MainActivity.java
package com.example.test6;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
/*定义组件*/
TestView tView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tView = (TestView)findViewById(R.id.testview1);
tView.setOnTouchListener(new mOnTouch());
}
class mOnTouch implements View.OnTouchListener{
@Override
public boolean onTouch(View v, MotionEvent event) {
int x1,y1;
/*获取坐标位置*/
x1 = (int)event.getX();
y1 = (int)event.getY();
/*在屏幕上点击*/
if (event.getAction() == MotionEvent.ACTION_DOWN){
/*按新坐标绘图*/
tView.getXY(x1,y1);
tView.invalidate();
return true;
}else if (event.getAction() == MotionEvent.ACTION_MOVE){/*在屏幕上拖动*/
/*按新坐标绘图*/
tView.getXY(x1,y1);
tView.invalidate();
return true;
}
return tView.onTouchEvent(event);
}
}
}
TestView.java
package com.example.test6;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class TestView extends View {
// 定义小球的初始坐标
int x=150,y=50;
public TestView(Context context, AttributeSet attrs){
super(context,attrs);
}
// 传递小球坐标位置
void getXY(int _x,int _y){
x=_x;
y=_y;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);//设置背景颜色为青色
Paint paint = new Paint();//定义画笔
paint.setStyle(Paint.Style.FILL);//设置画实心图形
paint.setAntiAlias(true);/*去锯齿*/
paint.setColor(Color.BLUE);/*设置画笔颜色*/
canvas.drawCircle(x,y,30,paint);/*画一个实心圆*/
paint.setColor(Color.WHITE);/*设置画笔颜色*/
canvas.drawCircle(x-9,y-9,6,paint);/*画一个实心圆*/
}
}