PreferenceActivity 中的 Toast 显示较晚
我想在用户单击 PreferenceActivity 中的 CheckBoxPreference 后立即显示 Toast。
myCheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(Prefs.this,
"test",
Toast.LENGTH_SHORT).show();
doSomething();
return false;
}
});
我还尝试将 Toast 放入 doSomething() 方法中,但它总是在整个方法处理完之后显示。我尝试使用 getBaseContext()
而不是 Prefs.this
,但没有帮助。 知道为什么 Toast 没有立即显示以及如何让它显示吗?
I want to show a Toast right after the user clicks on a CheckBoxPreference in my PreferenceActivity.
myCheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(Prefs.this,
"test",
Toast.LENGTH_SHORT).show();
doSomething();
return false;
}
});
I also tried to put the Toast into the doSomething() method, but it's always shown after the whole method is processed. I tried getBaseContext()
instead of Prefs.this
, but it didn't help.
Any idea why the Toast doesn't show up at once and how to make it do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发生这种情况是因为
onPreferenceClick
侦听器正在 UI 线程中运行。该线程也与处理显示 Toast 的线程相同。Toast#show
仅将消息推送到消息队列,然后运行代码以使Toast
显示。在onPreferenceClick
处理程序完全完成之后才会处理该队列。您可以尝试:
这将导致
Toast
发布到消息队列,然后您的doSomething
也会在 toast 后发布到队列。这样做的缺点是,在调用 doSomething 之前可能会处理一些 UI 消息。此外,如果doSomething
长时间运行,它将独占您的 UI 线程,并可能导致可能的 ANR 强制关闭。您可能需要考虑在 < 中运行doSomething
code>AsyncTask 如果需要超过 150ms 左右。This is happening because the
onPreferenceClick
listener is running in the UI thread. This thread is also the same as the one that handles displaying theToast
.Toast#show
only pushes a message onto the message queue that will then run code to make theToast
display. That queue won't be processed until after youronPreferenceClick
handler is completely finished.You can try:
This will cause the
Toast
to post to the message queue then yourdoSomething
will also be posted to the queue after the toast. The downside to this is that there could be UI messages that will be handled beforedoSomething
is called. Also, ifdoSomething
is long running it will monopolize your UI thread and could cause a possible ANR force close. You may want to think about runningdoSomething
in anAsyncTask
if it takes more than 150ms or so.我的解决方案是使用广播,并在 android 清单中注册一个接收器。
在 AndroidManifest 中:
发送广播:
接收器如下所示:
My solution is use broadcast, and make a receiver registered in android manifest.
in AndroidManifest:
sending broadcast:
receiver like below: