我在处理我的线程时遇到了真正的麻烦。简单来说,我希望一个红色方块在被触摸时出现在屏幕上,而在没有任何东西触摸屏幕时消失。我设法让它工作。
现在我正在尝试实现它,以便在触摸屏幕时出现红色方块,然后开始向手指移动。我想我会通过在触摸屏幕时运行一个线程来更新正方形的 X 和 Y 坐标来做到这一点。一旦我在 ACTION_DOWN 和 ACTION-UP 上启动和停止线程,我将尝试这个。
我试图实现只打印到系统输出的线程,当触摸屏幕时调用它,但当我移开手指时它不会停止。我尝试只在布尔值为真时运行线程。(这是在 ACTION_DOWN 发生时设置的。然后我设置 ACTION_UP 使其为假。
我在某处读到它不起作用,因为线程必须在它停止或其他东西之前完成。但我不明白这一点。
如果有人能告诉我哪里出了问题并向我解释,将不胜感激。
package com.mr.mwood.thumbinput;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MainActivity extends Activity {
boolean screenIsBeingTouched = false;
Thread th=new Thread(){
@Override
public void run(){
while (screenIsBeingTouched == true) {
try {
Thread.sleep(2000);
System.out.println("Thread is running ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
class SampleView extends SurfaceView {
int timer =0;
private final SurfaceHolder surfaceHolder;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// CONSTRUCTOR
public SampleView(Context context) {
super(context);
surfaceHolder = getHolder();
paint.setColor(Color.RED);
paint.setStrokeWidth(3);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:{
screenIsBeingTouched = true;
System.out.println("screenIsBeingTouched = true");
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
canvas.drawRect(30, 30, 80, 80, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
th.start();
break;
}
case MotionEvent.ACTION_UP:{
screenIsBeingTouched = false;
System.out.println("screenIsBeingTouched = false");
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
surfaceHolder.unlockCanvasAndPost(canvas);
break;
}
}
return true;
}
}
}