我有一个对话框片段,它初始化Google Plus视图,有时这些视图会失败,因此我想在显示给用户之前在该点处终止对话框。
我应该如何结束对话框创建过程?从返回Dialog对象的onCreateDialog中返回null会导致程序崩溃。
我有一个对话框片段,它初始化Google Plus视图,有时这些视图会失败,因此我想在显示给用户之前在该点处终止对话框。
我应该如何结束对话框创建过程?从返回Dialog对象的onCreateDialog中返回null会导致程序崩溃。
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setShowsDialog(false);
dismiss();
return null;
}
onActivityCreated()
Fragment 回调函数解决了此问题,该函数在 OnCreateDialog()
后被调用。我从 onCreateDialog()
返回一个有效的 Dialog,但使用 dismiss
标记应该关闭对话框。public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(dismiss) {
this.dismiss();
}
}
onViewCreated(View,Bundle)
,对于其他初始化,请使用onCreate(Bundle)
。要在片段活动的Activity.onCreate(Bundle)
调用时获取特定的回调,请在onAttach(Context)
中在Activity的生命周期上注册androidx.lifecycle.LifecycleObserver
,并在接收到Lifecycle.State.CREATED
回调时将其删除。 https://developer.android.com/reference/androidx/fragment/app/Fragment#onActivityCreated(android.os.Bundle) 。我已经创建了一个更更新的答案:https://dev59.com/b3TYa4cB1Zd3GeqPzNOS#69141205 - android developer其他答案有点过时,其中一个对我也没用(我在那里写了我的评论),所以这是我认为最新和有效的方法:
在onCreateDialog
回调中,编写成功时的逻辑。如果失败,则返回一些默认对话框(无论如何都不会使用),同时添加到生命周期的onStart
回调中以关闭DialogFragment(使用dismiss
或dismissAllowingStateLoss
):
fun Lifecycle.runOnStarted(runnable: () -> Unit) {
addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
runnable.invoke()
}
})
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//create the builder of the dialog, and then check if need to dismiss
if (needToDismiss) {
lifecycle.runOnStarted{
dismissAllowingStateLoss()
}
return builder.create()
}
另一种方法是使用Kotlin协程,而不使用我创建的辅助函数:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//create the builder of the dialog, and then check if need to dismiss
if (needToDismiss) {
lifecycleScope.launch {
whenStarted {
dismissAllowingStateLoss()
}
}
return builder.create()
}
或者您可以使用这个帮助函数,它使用 Kotlin 协程使代码更简洁:
fun LifecycleOwner.runOnStarted(runnable: () -> Unit) {
lifecycleScope.launch {
whenStarted{
runnable.invoke()
}
}
}
使用方法与以前一样简单:
runOnStarted{
dismissAllowingStateLoss()
}