免责声明:我检查了文档,自 2.1.0
以来,导航组件已支持对话框 fragment 。 (https://developer.android.com/jetpack/androidx/releases/navigation#2.1.0)
我遇到的错误
尝试从 DialogFragment
转到我的开始目标
时收到此错误:
java.lang.IllegalStateException:Fragment PostDistressDialog{829f5d1} (bbbc4926-684b-491b-9772-e0f0ffebe0af)} 未与 fragment 管理器关联。
PostDistressDialog
是使用导航组件从 JournalEntryFragment
(可以在下面的 map 中看到)调用的 DialogFragment
。 PostDistressDialog
不是 JournalEntryFragment
的内部类。它位于其自己的扩展 DialogFragment
我的导航图的图片
函数调用NavController
public class PostDistressDialog extends DialogFragment implements ISaveDatabase {
...
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
if (getArguments()!=null) {
...
// Set up the Alert Dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle(R.string.distressed_levels);
alertDialog.setMessage(R.string.distressed_how_feel_post);
// Inflate and set the layout for the dialog
View layout = View.inflate(getActivity(), R.layout.dialog_seekbar, null);
alertDialog.setView(layout);
....
// Add okay button
alertDialog.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Save post distress value in Journal Entry
mJournalEntry.setPostDistress(mTempDistressValue);
// Save to Journal Entry to database
// Check if journal entry empty
if(isJournalEntryEmpty(mJournalEntry)){
...
}
else{
// Give title if empty
if(mJournalEntry.getTitle().isEmpty()) {
....
// Save to database
new SaveDatabase(getContext(),PostDistressDialog.this).execute(mJournalEntry);
}
// Go to main menu
}
});
return alertDialog.create();
}
return null;
}
...
@Override
public void databaseSavingCompleted(){
NavHostFragment.findNavController(this).navigate(PostDistressDialogDirections.postDistressDialogToJournalListAction());
}
}
其中this
是public class PostDistressDialog extends DialogFragment
导航 XML 文件中的对话框
<dialog
android:id="@+id/postDistressDialog"
android:name="com.dgrullon.cbtjourney.dialogs.PostDistressDialog"
android:label="PostDistressDialog" >
<argument
android:name="postDistressDialogArguments"
app:argType="com.dgrullon.cbtjourney.pojo.JournalEntries"/>
<action
android:id="@+id/postDistressDialog_to_journalListAction"
app:destination="@id/journalList"
app:popUpTo="@id/journalList"
app:popUpToInclusive="true" />
</dialog>
最佳答案
当您添加到 setPositiveButton
的回调被触发时,
AlertDialog 会自动关闭对话框(从而删除您的 DialogFragment
)。因为您正在异步工作,所以在 DialogFragment 被销毁、与 FragmentManager 分离并从 NavController 中删除之后,您的 databaseSavingCompleted
方法将被调用 - 您正在泄漏对 DialogFragment 的引用(因为它会否则将被垃圾收集)。
因此,当 NavHostFragment.findNavController(this)
触发时,所有让它访问 NavController
的钩子(Hook)都已被清理。
如果您不希望按钮立即关闭对话框,则需要将 null
传递给 setPositiveButton()
,并在之后获取对按钮的引用该对话框是通过调用其 getButton()
API 并手动设置一个 OnClickListener
来创建的,该 OnClickListener 将启动您的 AsyncTask
(并禁用该按钮防止它被多次点击)。
关于Android 导航组件无法与对话框 fragment 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60405141/