我是一个非常新的android,作为一个项目,我正在做一个西蒙说游戏,我有一些问题代表顺序。
我尝试使用普通线程使其跟随一条线(例如,第一个按钮在X秒内变亮,然后关闭,然后是黄色......),但它没有成功,因为只有创建视图层次结构的线程才能操作该视图(在本例中是UI线程。),所以我必须使用runOnUiThread加载该线程中的所有方法,并且此时它几乎完美,因为现在序列显示但帧不显示。日志告诉我:
I / Choreographer:跳过116帧!应用程序可能在其主线程上做了太多工作。我一直在寻找各处,我找不到模拟序列的替代方案。我留下了方法的代码。 如果您需要更多信息,请告诉我。
感谢。
public void createSequence(){
new Thread() {
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
sequence.clear();
for(byte i=0;i<rounds;i++){
add=r.nextInt((4 - 1) + 1) + 1;
if (add == 1) {
btn1.setBackgroundResource(R.drawable.button1_pressed);
try {
Log.i("Waiting for 1.","Waiting for 1.");
Thread.sleep(time);
btn1.setBackgroundResource(R.drawable.button1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Value:", "1.");
} else if (add == 2) {
btn2.setBackgroundResource(R.drawable.button2_pressed);
try {
Log.i("Waiting for 2.","Waiting for 2.");
Thread.sleep(time);
btn2.setBackgroundResource(R.drawable.button2);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Value:", "2.");
} else if (add == 3) {
btn3.setBackgroundResource(R.color.colorpressedbutton3);
try {
Log.i("Waiting for 3.","Waiting for 3.");
Thread.sleep(time);
btn3.setBackgroundResource(R.drawable.button3);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Value:", "3.");
} else {
btn4.setBackgroundResource(R.color.colorpressedbutton4);
try {
Log.i("Waiting for 4.","Waiting for 4.");
Thread.sleep(time);
btn4.setBackgroundResource(R.drawable.button4);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Value:", "4.");
}
sequence.add(add);
}
}
});
}
}.start();
}
答案 0 :(得分:1)
你几乎得到了它。
您需要在单独的线程中实现 timing 逻辑,但需要在UI线程上实现 update (UI)逻辑。
这样的事情:
void setState(final Button b, final int state) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
b.setBackgroundResource(state);
}
});
}
void runSequence() {
new Thread() {new Runnable() {
@Override
public void run() {
sequence.clear();
for(byte i=0;i<rounds;i++){
add=r.nextInt((4 - 1) + 1) + 1;
if (add == 1) {
setState(btn1,R.drawable.button1_pressed);
try {
Log.i("Waiting for 1.","Waiting for 1.");
Thread.sleep(time);
setState(btn1, R.drawable.button1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Value:", "1.");
} else if (add == 2) {
....
}
}).start();
}