我尝试按下按钮创建一个进度条。只有在完成其他所有操作后,才能看到进度条。
MainActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
} });
我可以强制UI线程加入吗?
编辑:完成onClick代码
public void onClick(View view) {
if (view == etLocation){
etLocation.setText("");
}
if (view == btnGo){
//progressBar.setVisibility(View.VISIBLE);
MainActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
} });
Thread buttonpress = new Thread(new Runnable() {
public void run()
{
buttonGo();
}
});
buttonpress.run();
}
if (view == datePicker){
new DatePickerDialog(MainActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
答案 0 :(得分:0)
UI线程是故意异步的。应用程序层的工作是告诉UI线程要执行什么,不是时这样做。
如果您的应用程序逻辑依赖于UI更新,那么您应该认为您的应用程序逻辑过于紧密耦合。
答案 1 :(得分:0)
runOnUiThread是异步的。仔细查看代码,我也看到了一个简单的解决方法:
//progressBar.setVisibility(View.VISIBLE);
Thread buttonpress = new Thread(new Runnable() {
public void run()
{
buttonGo();
}
});
//Move runOnUiThread down. The thread above will not start doing its thing until you tell it to run
MainActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
buttonpress.run();//TO HERE. Now the progressbar will be initialized, THEN the thread will start
} });
//buttonpress.run(); MOVE THIS
我基本上做的是将runOnUiThread向下移动,因此它可以访问ButtonPress线程。
然后,在progressBar可见之后,运行该线程。