- Java code
package com.example.testontouch;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.os.Bundle;import android.view.MotionEvent; public class MainActivity extends Activity{ private float x = 0; float y = 0; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { while(true) { System.out.println(x+" "+y); } } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("kaishi"); } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN) { x = event.getX(); y = event.getY(); timer.schedule(task,10, 1000); } else if(event.getAction() == MotionEvent.ACTION_UP) { timer.cancel(); } return false; }}
------解决方案--------------------
这样改:
首先,在
private float x = 0;
前面定义一个
private boolean hasLoop = true;
然后,将while(true)这句改为while(hasLoop)
再次,将timer.cancel();改为hasLoop = false;
------解决方案--------------------
测试一下有没有进入 else 块,如果没有试一试return true