android - 在DialogFragment中观察Viewmodel Livedata

标签 android mvvm android-dialogfragment android-viewmodel

我有一个Viewmodel,其中包含一些Livedata参数。这些Livedata参数(clickedItem)更改之一旨在触发DialogFragment

DialogFragmentOnCreateDialog(savedInstanceState: Bundle?)方法中,我正在提取并使用上述Livedata参数中的数据来做某件事。

这是clickedItem观察器方法:

clickedItem.observe(viewLifecycleOwner, Observer { clickedItem ->
                if (clickedItem != null && !dialogIsDisplayed) {
                    showAddItemDialog()
                }
            })

这是DialogFragmentOnCreateDialog(savedInstanceState: Bundle?)方法:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it)

            binding = DataBindingUtil.inflate(
                requireActivity().layoutInflater,
                R.layout.business_inventory_selection_item_dialog, null, false
            )

            //Attach viewmodel to this fragment.
            setupViewModel()

            builder.setView(binding.root)

            bindView(viewModel.clickedItem.value!!)

            builder.create()

        } ?: throw IllegalStateException("Activity cannot be null")
    }

这是setupViewModel()方法:
private fun setupViewModel() {
        activity?.run {
            viewModel = ViewModelProviders.of(this)
                .get(BusinessInventorySelectionViewModel::class.java)
            with(viewModel) {
                itemBrand.value = null
                unitOfMeasurement.value = null
            }
        }
        bindViewModel()
    }

private fun bindViewModel() {
    binding.apply {
        businessinventoryselectionviewmodel = viewModel
        lifecycleOwner = this@ItemSelectionDialogFragment
    }
}

现在的问题是:当我尝试使用封装在clickedItem中的数据时,我发现它具有上次更改时的数据,而不是导致DialogFragment触发的最新数据。
在开始利用clickedItem中的最新数据之前,我被迫浏览了clickedItem中存储的所有数据。

最佳答案

我找到了解决此问题的方法,如下所示:

我没有在bindView(viewModel.clickedItem.value!!)中调用onCreateDialog(savedInstanceState: Bundle?),而是在onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)方法中调用了它:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        bindView(viewModel.clickedItem.value!!)
        return binding.root
    }

这样就解决了问题。

关于android - 在DialogFragment中观察Viewmodel Livedata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507987/

相关文章:

android - 从数据库中获取数据时如何对列表中的行进行分组并给出标题

android - android库项目中的ContentProvider

android - 列出 Android 4+ 中特定日期的事件(ALL_DAY 问题)

java - 唯一约束失败,SQLite,Java

c# - 如何使用DataGrid和MVVM添加行

c# - 添加控件以从ViewModel查看

Android:如何强制在 onBind() 之前调用 onStartCommand()?

wpf - 在 View 模型之间传递数据的正确方法是什么?

android - 如何在 AlertDialog 中使用 ViewPager? - Android 4.0+

java - NullPointerException 尝试获取 DialogFragment 的 PositiveButton