好吧,我一直在寻找答案,但没有一个对我有用。我有一个按钮,当它被按住时,应该继续在屏幕上移动图像。但由于某种原因,当我点击按钮时,它只会冻结我的 Kindle。我认为线程是问题的一部分,但我不确定。这是代码:
package com.evilsea.darkages;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener, Runnable {
ImageView leftImageButton;
boolean leftButtonDown = false;
ImageView knight;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread1 = new Thread(this);
thread1.start();
this.run();
}
public void addListenerOnLeftButton() {
leftImageButton = (ImageView) findViewById(R.id.left_button);
leftImageButton.setOnTouchListener(leftButtonlistener);
knight = (ImageView) findViewById(R.id.knight_image);
}
OnTouchListener leftButtonlistener = new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
leftButtonDown = true;
try {
while(leftButtonDown) {
Thread.sleep(10);
moveLeft(5);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
leftButtonDown = false;
break;
}
return false;
}
};
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
@Override
public void run() {
addListenerOnLeftButton();
}
public void moveLeft(int speed) throws InterruptedException {
knight.setLeft(knight.getLeft() -speed);
}
}
顺便说一句,我刚开始使用 android,所以如果这是一个明显的问题,我很抱歉。谢谢!非常感激。