我是Android开发的新手。我正在尝试显示 ProgressDialog
。我看到很多教程说显示对话框必须使用线程。正如您所看到的,代码片段正在使用线程。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
refreshFromFeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
dialog.dismiss();
}
protected void onRefresh(View view) throws InterruptedException {
refreshFromFeed();
}
日志显示花了5秒钟,然而,我在屏幕上看不到任何对话框,我可以在屏幕上做任何事情。甚至我在物理设备上使用。我使用过调试模式。没有例外。
onRefresh
是onClick
在其上声明的xml事件。
答案 0 :(得分:0)
我已经对您的代码进行了一些更改,请仔细阅读。
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo",String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
}
答案 1 :(得分:0)
您在显示对话框后立即解雇对话框。 也许你想移动你的“dialog.dismiss();”在线程内部。请记住,您需要关闭UI线程上的对话框,否则会导致您的应用崩溃:
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
};
th.start();
}
我看到许多用于显示对话框的教程必须使用线程。
你没有明确需要一个线程来显示ProgressDialog,这只是一个在5000毫秒后解除它的例子
答案 2 :(得分:0)
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"Loading","Wake up after some sleep");
Thread th = new Thread() {
public void run() {
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis() / 1000));
try {
Thread.sleep(5000);
dialog.dismiss(); // dismiss your dialog here
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis() / 1000));
}
};
th.start();
}
答案 3 :(得分:0)
您仍然在UI线程中运行ProgressDialog。
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
在此行之后创建的新主题,而不是在此行之前!