为什么睡眠执行第一,比code在它上面的Android? [英] Why the Sleep executes first and than the code above it in android?
本文介绍了为什么睡眠执行第一,比code在它上面的Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在try块首先执行为什么,我要的颜色来改变第一,那么就应该睡FO 5000毫秒。我的意思是系统前的颜色变化睡。
私人OnClickListener CheckAnswer =新OnClickListener(){
公共无效的onClick(查看为arg0){
// TODO自动生成方法存根 disableButtons();
巴顿传入=(按钮)为arg0;
如果(incoming.getText()。的toString()。等于(Q.getAnswer()))
{
incoming.setBackgroundColor(Color.GREEN);
正确++;
得分+ = 15;
}
其他
{
incoming.setBackgroundColor(Color.RED);
错++;
如果(C1.getText()。的toString()。等于(Q.getAnswer()))
C1.setBackgroundColor(Color.GREEN);
否则,如果(C2.getText()。的toString()。等于(Q.getAnswer()))
C2.setBackgroundColor(Color.GREEN);
否则,如果(C3.getText()。的toString()。等于(Q.getAnswer()))
C3.setBackgroundColor(Color.GREEN);
modifyScore(); }
尝试{
视频下载(5000);
}赶上(InterruptedException的E){
// TODO自动生成catch块
e.printStackTrace();
}
questionGenerator();
}
};`
解决方案
我猜是因为视图的属性被更新,但屏幕重绘被卡住你的睡眠后面。不睡在主线程。
而不是建立在你的活动的OnCreate处理程序和发布延迟可运行它。
专用处理器mHandler;
保护无效的onCreate(捆绑savedInstanceState){
mHandler =新的处理程序();
}
...
私人OnClickListener CheckAnswer =新OnClickListener(){
公共无效的onClick(查看视图){
//修复了看法
mHandler.postDelayed(新的Runnable(){
@覆盖
公共无效的run(){
questionGenerator();
}
},10000);
}
}
Why is the try block executed first, i want the colors to change first and then it should sleep fo 5000ms. i mean the system sleeps before the colors changes. private OnClickListener CheckAnswer =new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
disableButtons();
Button incoming=(Button) arg0;
if(incoming.getText().toString().equals(Q.getAnswer()))
{
incoming.setBackgroundColor(Color.GREEN);
correct++;
score+=15;
}
else
{
incoming.setBackgroundColor(Color.RED);
wrong++;
if(C1.getText().toString().equals(Q.getAnswer()))
C1.setBackgroundColor(Color.GREEN);
else if(C2.getText().toString().equals(Q.getAnswer()))
C2.setBackgroundColor(Color.GREEN);
else if(C3.getText().toString().equals(Q.getAnswer()))
C3.setBackgroundColor(Color.GREEN);
modifyScore();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
questionGenerator();
}
};`
解决方案
I'd guess because the properties of the view are updated, but the screen redraw is stuck behind your sleep. DO NOT sleep on the main thread.
Instead create a Handler in the onCreate of your Activity and post a delayed Runnable to it.
private Handler mHandler;
protected void onCreate(Bundle savedInstanceState) {
mHandler = new Handler();
}
...
private OnClickListener CheckAnswer = new OnClickListener() {
public void onClick(View view) {
// fix up view
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
questionGenerator();
}
}, 10000);
}
}
这篇关于为什么睡眠执行第一,比code在它上面的Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文