编写时遇到的问题:声明int变量时没有声明public,在重写ondraw方法时。没有继承,并且没有canvas;布局时Lineration写在了外面;重绘的语句不会写;
第一个文件:
package com.android.test;
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 x;
public float y;
public DrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint paint =new Paint();
paint.setColor(Color.GREEN);
canvas.drawCircle(x,y, 15, paint);
}
}
第二个文件:
package com.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
public class MoveBallActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout =(LinearLayout)findViewById(R.id.root);
final DrawView drawView =new DrawView(this);
drawView.setMinimumHeight(400);
drawView.setMinimumWidth(400);
drawView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
drawView.x= event.getX();
drawView.y= event.getY();
drawView.invalidate();
return true;
}
});
layout.addView(drawView);
}
}