android 当我在使用Fragment对话框时在暗模式和亮模式之间切换时,如何安全地重新创建我的Activity?

ie3xauqp  于 2023-06-27  发布在  Android
关注(0)|答案(2)|浏览(259)

bounty将在59分钟后到期。此问题的答案有资格获得+50声望奖励。Mohamed Jihed Jaouadi正在寻找一个答案从一个有信誉的来源

我有一个对话框片段,它显示了一个图像,该图像的字节码被传递给构造函数。
当对话框出现时,我处于黑暗模式,并尝试将模式更改为亮一,然后我回到屏幕上,屏幕显示全白色,我得到以下错误:

  1. Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment *.*.*.PictureLoaderDialogFragment: could not find Fragment constructor

我示例化我的片段对话框如下:

  1. class PictureLoaderDialogFragment(
  2. private var bitmapByteArray: ByteArray?
  3. ) : DialogFragment(){
  4. companion object {
  5. @JvmStatic
  6. fun newInstance(
  7. bitmapByteArray: ByteArray? = null
  8. ) = PictureLoaderDialogFragment(bitmapByteArray)
  9. }
  10. }

你知道该怎么修吗

np8igboo

np8igboo1#

此错误是由向片段的构造函数传递参数引起的。
这与片段的生命周期及其与活动的相互作用有关。Android中的Fragment被设计为可重用的,并且可以根据Activity的生命周期在不同的时间点创建和销毁。在创建片段时,Android系统会使用一个没有参数的空构造函数,在设备配置发生变化(本例中为设备主题发生变化)后,创建一个新的片段示例。
为了解决这个问题,有三种解决方案:
1.在Bundle中保存参数
1.使用FragmentFactory
1.使用Dependency Injection(DI)
由于您在代码中使用了newInstance方法,下面的示例显示了如何使用它,遵循 * 第一种方式 * 并将参数保存在Bundle中:

  1. class PictureLoaderDialogFragment : DialogFragment() {
  2. //...
  3. companion object {
  4. fun newInstance(bitmapByteArray: ByteArray? = null): PictureLoaderDialogFragment {
  5. val fragment = PictureLoaderDialogFragment()
  6. val args = Bundle()
  7. args.putByteArray("bitmap", bitmapByteArray)
  8. fragment.arguments = args
  9. return fragment
  10. }
  11. }
  12. }

您可以访问PictureLoaderDialogFragment中传递的参数:

  1. val bitmapByteArray = arguments?.getByteArray("bitmap")
  2. bitmapByteArray?.let {
  3. val image = BitmapFactory.decodeByteArray(it, 0, it.size)
  4. imageView.setImageBitmap(image)
  5. }

您可以显示DialogFragment

  1. PictureLoaderDialogFragment.newInstance(bitmapByteArray).show(manager, tag)

This article解释了如何使用FragmentFactory,方法如下 * 第二种解决方法 *

  • 解决 * 的第三种方法-here,你可以学习如何使用依赖注入使用Hilt
展开查看全部
rqmkfv5c

rqmkfv5c2#

该错误消息表明您的PictureLoaderDialogFragment的构造函数存在问题。您已经实现的newInstance方法对于向DialogFragment传递参数是正确的。但是,问题可能在于构造函数本身。
要修复此问题,请确保PictureLoaderDialogFragment类具有不带参数的构造函数。代码可以是这样的:

  1. class PictureLoaderDialogFragment : DialogFragment() {
  2. private var bitmapByteArray: ByteArray? = null
  3. companion object {
  4. @JvmStatic
  5. fun newInstance(bitmapByteArray: ByteArray? = null): PictureLoaderDialogFragment {
  6. val fragment = PictureLoaderDialogFragment()
  7. fragment.bitmapByteArray = bitmapByteArray
  8. return fragment
  9. }
  10. }
  11. // Rest of your fragment implementation...
  12. }

我刚刚从PictureLoaderDialogFragment类中删除了构造函数参数,并通过单独的setter方法为bitmapByteArray赋值。newInstance工厂方法负责创建片段的新示例并适当地设置参数值。
请确保更新片段实现的其余部分,以正确访问bitmapByteArray变量。

展开查看全部

相关问题