我正在尝试显示进度对话框并在runOnUiThread中更新它 但进度条从未显示过。当我用" new Thread"替换runOnUiThread时它工作正常。但我希望它能与runOnUiThread一起使用
这是我的代码,我删除了不必要的代码
public class test extends Activity {
private ProgressDialog progress;
Handler progressBarHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testing();
}
public void testing() {
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
runOnUiThread(new Runnable() {
@Override
public void run() {
//do some work
for (int i =0; i<100;i++){
//some work
progressBarHandler.post(new Runnable() {
@Override
public void run() {
progress.setProgress(finalCount);
}
});
}
}
}
答案 0 :(得分:0)
试试这个
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
Handler workHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
workHandler = new Handler(new HandlerThread("workHandlerThread").getLooper());
workHandler.post(new Runnable() {
@Override
public void run() {
//Do some work
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setProgress(/*work result*/);
}
});
}
});
}
}
我的想法是你对HandlerThread的工作绑定到workHandler
,并使用runOnUiThread()