package com.example.crazy; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class NewView extends View{ //定义圆的出事位置 public float currentX=40; public float currentY=50; //定义画笔 Paint p=new Paint(); public NewView(Context context) { super(context); // TODO Auto-generated constructor stub } public NewView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public NewView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); //设置画笔的颜色 p.setColor(Color.RED); //绘制一个小圆 canvas.drawCircle(currentX, currentY, 15, p); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub //设置当前组件的两个属性 this.currentX=event.getX(); this.currentY=event.getY(); //通知组件重置 this.invalidate(); //返回true代表时间已经处理 return true; } }
<LinearLayout 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=".MainActivity" android:orientation="vertical" > <com.example.crazy.NewView android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
主页面MainActivity
package com.example.day1_two; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
效果图如下:圆随着鼠标二移动