我想要做的是让我的程序在更改图像之前等待 3 秒。我做了我的研究,似乎这可以解决它,但它告诉我我需要使 c1 和 c2 成为最终的。但是,这将破坏我的其余代码。
我试图在 3 秒后运行这两行:
c1.getImg().setImageResource(R.drawable.facedown);
c2.getImg().setImageResource(R.drawable.facedown);
有什么解决方案?谢谢!
private Thread thread;
public void checkMatch(int num) {
flips++;
President c1 = null;
President c2 = cards.get(num - 1);
if (flips % 2 != 0) {
return;
} else {
for (President c : cards) {
if (c.isFlipped() == true && c.isMatched() == false && c != c2) {
c1 = c;
}
}
if (c1.getPresident() == c2.getPresident()) {
cards.get(c1.getCard() - 1).setMatched(true);
cards.get(c2.getCard() - 1).setMatched(true);
} else {
cards.get(c1.getCard() - 1).setFlipped(false);
cards.get(c2.getCard() - 1).setFlipped(false);
thread = new Thread() {
@Override
public void run() {
try {
synchronized (this) {
wait(3000);
}
} catch (InterruptedException ex) {
}
// TODO
//THESE TWO LINES ARE THE ONES I WANT TO RUN AFTER 3 SECONDS
c1.getImg().setImageResource(R.drawable.facedown);
c2.getImg().setImageResource(R.drawable.facedown);
}
};
thread.start();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent evt) {
if (evt.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (thread) {
thread.notifyAll();
}
}
return true;
}
09-07 17:04:19.937: E/AndroidRuntime(6822): FATAL EXCEPTION: Thread-4693
09-07 17:04:19.937: E/AndroidRuntime(6822): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.View.requestLayout(View.java:15473)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.View.requestLayout(View.java:15473)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.View.requestLayout(View.java:15473)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.View.requestLayout(View.java:15473)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:318)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.view.View.requestLayout(View.java:15473)
09-07 17:04:19.937: E/AndroidRuntime(6822): at android.widget.ImageView.setImageResource(ImageView.java:352)