下面是一个小例子,跟随手指的小球
创建一个继承自View的类,用来绘制圆形
package WangLi.CustomView.Space;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
public float currentX = 40;
public float currentY = 50;
public DrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
//创建画笔
Paint p = new Paint();
//设置画笔颜色
p.setColor(Color.RED);
//绘制一个小圆(作为小球)
canvas.drawCircle(currentX, currentY, 15, p);
}
下面是该应用的Activity类
package WangLi.CustomView.Space;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.view.MotionEvent;
public class CustomView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取LinearLayout布局容器
LinearLayout root = (LinearLayout)findViewById(R.id.root);
//创建DrewView组件
final DrawView draw = new DrawView(this);
//设置自定义组件的最大宽度,高度
draw.setMinimumWidth(300);
draw.setMinimumHeight(500);
//为draw组件绑定Touch事件
draw.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View view, MotionEvent event)
{
//修改draw组件的currentX,currentY两个属性
draw.currentX = event.getX();
draw.currentY = event.getY();
//通知draw组件重绘
draw.invalidate();
//返回true表明处理方法已经处理该事件
return true;
}
});
root.addView(draw);
}
}
运行效果如下
这个红色的球,在手机模拟器中,鼠标按下(模拟Touch事件)就会跟着光标移动