android-fragments Android.重新创建片段视图后数据绑定不起作用

jjjwad0x  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(201)

我使用MVVM和数据绑定,在我从片段A导航(使用jetpack导航)到片段B,然后返回片段A之后,片段A的视图被重新创建。
为了解决这个问题,我在fragment类中创建了一个字段来保存我的视图:

private var contentView: View? = null

  override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {       
        if (contentView == null) {
            contentView= FragmentPhotoDetailBinding.inflate(inflater, container, false).apply {
                lifecycleOwner = viewLifecycleOwner
                viewBinding = this
                vm = viewModel
            }.root
        }
        return contentView !!
    }

它工作了,但是现在在重新创建片段视图之后,数据绑定对我不起作用。
视图模型更新实时数据上的数据,但订阅者不会以任何方式对其做出React。
请帮我解决这个问题。

**P.S.**如果我没有在字段中保存视图,而是在每次调用onCreateView()后创建一个新视图,那么数据绑定就可以工作了。

o8x7eapl

o8x7eapl1#

这样做:

private var _binding: View? = null
  /*
   *Transform to immutable - use this for updating binding
   *properties like in data binding
   */
   private val binding: View get() = _binding!!

  override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {       
        _binding = FragmentPhotoDetailBinding.inflate(inflater, container, false)
        binding.apply {
                lifecycleOwner = viewLifecycleOwner
                viewBinding = this
                vm = viewModel
            }
        }
        return binding.root!!
    }

  override fun onDestroy(){
     super.onDestroy()
    //Nullify since it is not automatically garbage collected
     _binding = null
}

如果您希望重用先前已膨胀,则可以在onCreateView中对_binding添加空检查,并删除onDestroy_binding的无效

if (_binding == null) { 
   _binding = FragmentPhotoDetailBinding.inflate(inflater, container, false)
}

相关问题