本人刚开始学习android,跟着书写了个程序,这个程序是会有一个东西随着手指拖动而移动,编译完没有问题,但是在手机上运行的时候却是意外停止,代码和书上写的一模一样,求大神指导
DrawView.java的代码:
/**
*
*/
package com.example.customview;
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;
/**
- Description:
-
网站: 疯狂Java联盟 -
Copyright (C), 2001-2014, Yeeku.H.Lee -
This program is protected by copyright laws. -
Program Name: -
Date: - @author Yeeku.H.Lee kongyeeku@163.com
-
@version 1.0
*/
public class DrawView extends View
{
public float currentX = 40;
public float currentY = 50;
// 定义、并创建画笔
Paint p = new Paint();
public DrawView(Context context)
{
super(context);
}
public DrawView(Context context , AttributeSet set)
{
super(context ,set);
}
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
// 设置画笔的颜色
p.setColor(Color.RED);
// 绘制一个小圆(作为小球)
canvas.drawCircle(currentX, currentY, 15, p);
}// 为该组件的触碰事件重写事件处理方法
@Override
public boolean onTouchEvent(MotionEvent event)
{
// 修改currentX、currentY两个属性
currentX = event.getX();
currentY = event.getY();
// 通知当前组件重绘自己
invalidate();
// 返回true表明该处理方法已经处理该事件
return true;
}
}
CustomView.java的代码:
package com.example.customview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
/**
- Description:
-
site: crazyit.org -
Copyright (C), 2001-2014, Yeeku.H.Lee -
This program is protected by copyright laws. -
Program Name: -
Date: - @author Yeeku.H.Lee kongyeeku@163.com
- @version 1.0 */ public class CustomView extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_view); // 获取布局文件中的LinearLayout容器 LinearLayout root = (LinearLayout) findViewById(R.id.root); // 创建DrawView组件 final DrawView draw = new DrawView(this); // 设置自定义组件的最大宽度、高度 draw.setMinimumWidth(300); draw.setMinimumHeight(500); root.addView(draw); } }
custom_view.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root">