最近在学习自定义控件,菜鸟一枚,自己写的东西大神勿喷,仅作交流
废话不多说,直接上码
package com.jingcai.fu.planegame;
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;
/**
* Created by Administrator on 2016/3/11.
*/
public class DrawView extends View {
public float currentX= 40;
public float currentY= 50;
//定义创建画笔
Paint paint =new Paint();
public DrawView(Context context) {
super(context);
}
public DrawView(Context context,AttributeSet set) {
super(context,set);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置画笔的颜色
paint.setColor(Color.RED);
canvas.drawCircle(currentX,currentY,15,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//当前组件的currentX,currentY的两个属性
this.currentX = event.getX();
this.currentY = event.getY();
//通知该组件重绘
this.invalidate();
//返回true表明方法已经处理事件
return true;
}
}
还有xml布局
<?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.jingcai.fu.planegame.MainActivity">
<com.jingcai.fu.planegame.DrawView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
在代码中不需要做处理 一个跟着手指运动的view就出来了