在 PreferenceActivity 中显示 ProgressDialog
当我尝试在 onPreferenceChange
侦听器中显示 ProgressDialog
(简单的微调类型)时,我遇到了一个非常有趣的问题。
public class SettingsActivity extends PreferenceActivity {
private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
ListPreference pref= (ListPreference) findPreference("myPreference");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
dialog = ProgressDialog.show(SettingsActivity.this, "", "Doing stuff...", true);
SystemClock.sleep(2000);
}
return true;
}
}
ProgressDialog
会显示,但要等到该方法(在本例中为 sleep
)完成后才会显示。我做错了什么?
I've got a quite interesting issue when I try to display a ProgressDialog
(the simple, spinner type) within a onPreferenceChange
listener.
public class SettingsActivity extends PreferenceActivity {
private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
ListPreference pref= (ListPreference) findPreference("myPreference");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
dialog = ProgressDialog.show(SettingsActivity.this, "", "Doing stuff...", true);
SystemClock.sleep(2000);
}
return true;
}
}
The ProgressDialog
shows up, but not until the method (sleep
in this case) has finished. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在主 UI 线程上休眠,这会阻止操作系统处理应用程序的事件。这将阻止您的应用程序重绘,并且正如您所发现的,可以阻止新窗口的实际出现。
与其睡觉,不如试试这个:
You're sleeping on the main UI thread, which stops the operating system from handling your application's events. This will stop your app from redrawing and as you discovered, can prevent new windows from actually appearing.
Instead of sleeping, try this:
您可以使用
AsyncTask
在单独的线程中运行该函数(请参阅 http://developer.android.com/resources/articles/painless-threading.html)如果您只想调用
sleep
方法,这可能有点不必要,但即使对于其他会阻塞 UI 线程的方法也应该有效。你可以这样做:
然后使用下面的代码调用它:
You can use
AsyncTask
to run the function in a separate thread (see http://developer.android.com/resources/articles/painless-threading.html)This is probably a bit unnecessary if you just want to invoke a
sleep
method, but should work even for other methods that otherwise would block the UI thread.You could do something like this:
And than call it using the code below: