我在使用我的线程时遇到了麻烦。简单来说,我想要一个红色方块在触摸时出现在屏幕上,当没有任何东西触摸屏幕时消失。我设法让这个工作。
现在我正在尝试实现它,以便在触摸屏幕时出现红色方块,然后开始向手指移动。我想我会通过在触摸屏幕时运行一个线程来执行此操作,这会更新X& Y广场的坐标。一旦我开始并在ACTION_DOWN和ACTION-UP上停止线程,我将尝试这个。
我试图实现刚刚打印到系统输出的线程,并在触摸屏幕时调用它,但在我移开手指时不会停止。我尝试仅在布尔值为true时运行线程。 (当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;
}
}
}
答案 0 :(得分:1)
只需在此处更新并尝试
@Override
public boolean onTouchEvent(MotionEvent event) {
//your code
return false; // UPDATE HERE
}
答案 1 :(得分:0)
我有一些提示: