gpt4 book ai didi

Android DialogFragment : can I re-use, 还是我必须新建一个?

转载 作者:行者123 更新时间:2023-11-30 02:34:39 25 4
gpt4 key购买 nike

我想弹出一个时间选择器和一个日期选择器,在一个 Activity 中不止一次。

我不清楚我是否应该为每个创建一个实例并根据需要显示它们,或者我是否应该在每次需要弹出对话框时创建新实例。

我对 findFragmentByTag/findFragmentById 感到很困惑。似乎只有当前显示时才能找到该 fragment ?

但是如果找不到它并且我制作了一个新 fragment 并用相同的标签显示它,我会得到一个 IllegalStateException。如何在 onCreate 中恢复 fragment ?

目前,我正在这样做:

FragmentManager fm = getSupportFragmentManager();

if (savedInstanceState == null) {
timePicker = new RadialTimePickerDialog();
datePicker = new CalendarDatePickerDialog();
fm.beginTransaction().add(timePicker, FRAGMENT_TIME_PICKER)
.add(datePicker, FRAGMENT_DATE_PICKER).commit();
} else {
timePicker = (RadialTimePickerDialog)
fm.findFragmentByTag(MedicationCollapsePanel.FRAGMENT_TIME_PICKER);
datePicker = (CalendarDatePickerDialog)
fm.findFragmentByTag(MedicationCollapsePanel.FRAGMENT_DATE_PICKER);
}

正如我所提到的,这无法真正找到 fragment ,而且几乎同样糟糕,它会在 Activity 启动时立即显示它们,这是我不想要的。

谢谢。

最佳答案

我假设这些类是来自 gitHub 并在谷歌搜索顶部弹出的同名类。

它们扩展了 dialogFragments。

DialogFragments 会在它们被解散时使用 fragment 管理器自行删除。您可以从下面的链接查看源代码并获取此说明:

关闭():

Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/app/DialogFragment.java#DialogFragment.onDismiss%28android.content.DialogInterface%29

因此,它们在被解雇后不可重用,因为它们将通过调用底层上下文并自行获取 fragment 管理器来自动取消附加。而是创建一个新实例并显示它们,或者您可以尝试覆盖它们的默认行为。您可以尝试改变他们被解雇后的行为,或者首先阻止他们被解雇(例如隐藏他们)。

关于Android DialogFragment : can I re-use, 还是我必须新建一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com