我知道这个问题已经在StackOverflow上被问到并回答了..但我似乎无法让变量起作用。有人建议我使用这个代码但仍然没有。简要说明是我需要一个功能,当你的手指在屏幕上向下时运行(显然无法在UI中完成)。这样一个新的线程.. x,y,高度,宽度。
//global variables
boolean var = false;
//instance variable to check if thread has started running for first time
int x, y, width, height;
// variables as instance variables
boolean fingerdown;
Thread myThread = new Thread()
{
@Override
public void run()
{
while(fingerdown==true);
{
// class object = new class() in the activity area
object.function(this.x ,this.y , this.height, this.width);
}
}
};
// this section is within the UI function that detections MotionEvents
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
this.x = event.getX();
this.y = event.getY();
this.width = widthf;
this.height = heightf;
fingerdown = true;
if(!var)
{
var = true;
myThread.start();
}
}
if (event.getAction() == MotionEvent.ACTION_UP)
{
fingerdown = false
}
答案 0 :(得分:1)
private class myThread extends Thread{
int x, y;
public myThread(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
// your stuff
}
}
要调用此线程,请使用
myThread obj = new myThread(100,200);
obj.start();
答案 1 :(得分:1)
构建named
类而不是anonymous
。
public class TestThread implements Runnable
{
private volatile boolean fingerdown;
@Override
public void run()
{
....
}
public void stopThread()
{
fingerdown=false;
}
}
事件处理程序代码:
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
this.x = event.getX();
this.y = event.getY();
this.width = widthf;
this.height = heightf;
fingerdown = true;
if(!var)
{
mythread=new TestThread();
myThread.start();
}
}
if (event.getAction() == MotionEvent.ACTION_UP)
{
if(mythread!=null)
{
mythread.stopThread();
mythread=null;
}
}