0

我是 android 的新手,我想制作一个简单的程序来检测触摸坐标并绘制一个圆圈和触摸路径,我制作了一个简单的程序,在触摸周围画一个圆圈并跟随它,但我仍然可以做路径的触摸。当我用路径启动程序时它崩溃,当我删除它正常工作的路径时......

public class MainActivity extends Activity {

    float x = 0;
    float y = 0;
    LinearLayout layout; //declarea variabilor pentru desenarea cercului

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //specificarea 
        layout = (LinearLayout)findViewById(R.id.layout); //gasirea id 
        layout.addView(new CustomView(MainActivity.this));
    }

    public class CustomView extends View { //crearea unei mape pentru canvas
        Bitmap mBitmap;
        Paint paint;
        Path path;

        public CustomView(Context context) {
        super(context);
        mBitmap = Bitmap.createBitmap(640, 1024, Bitmap.Config.ARGB_8888);
            paint = new Paint();
            path = new Path();
            paint.setColor(Color.BLUE);//culoare cercului desenat
            paint.setStyle(Style.FILL);
        }

    protected void onDraw(Canvas canvas) {//desenarea cercului la atingere
        super.onDraw(canvas);
        canvas.drawPath(path,paint);
        canvas.drawCircle(x, y, 25, paint);
    }

    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();

        switch (action){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(event.getX(), event.getY());
                path.lineTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                x = event.getX();
                y = event.getY();
                path.lineTo(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                path.lineTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
            break;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
4

1 回答 1

0

您没有初始化path. 最有可能的是,您的程序因NullPointerException. 尝试在CustomView构造函数中添加它:

path = new Path();

将来,当您发布有关您的 Android 程序崩溃的信息时,如果您发布崩溃的 logcat 输出将是最有帮助的。

于 2013-02-26T19:33:48.763 回答