Android FragmentManager和Fragment Result API

3

如何理解这样一种情况:使用新的Fragment Result API的片段F从其他两个片段A、B中获取结果,但是它只能接收来自A片段而不是B片段的结果,因为B片段使用了一个不同的FragmentManager(我不知道为什么)。为什么会出现这样的情况?两个以相同方式调用的片段最终具有相同的Activity但不同的FragmentManager?函数调用如下:

//以下代码无法正常工作。结果集设置后,监听器并没有被调用

private fun navigateToItemLocation() {

        setFragmentResultListener(REQUEST_LOCATION_KEY) { s: String, bundle: Bundle ->

            val locationId = bundle.getParcelable<ParcelUuid>(LOCATION_ID)!!.uuid
            viewModel.viewModelScope.launch(Dispatchers.IO) {
                val location = LocationRepository().get(locationId)!!
                changeItemLocation(location)
            }
        }


        val action = ItemRegistrationPagerHolderDirections.actionNavItemRegistrationPagerToNavStockLocationSelection()
        findNavController().navigate(action)
    }

//这个工作得很好:

private fun navigateToItemDetails(item: Item2) {

        setFragmentResultListener(SELECTED_ITEM_KEY) { s: String, bundle: Bundle ->

            val propertySetId = bundle.getParcelable<ParcelUuid>(SELECTED_ITEM_SET_ID)!!.uuid
            clearFragmentResultListener(SELECTED_ITEM_KEY)

            viewModel.viewModelScope.launch(Dispatchers.IO) {
                val repository = PropertySetRepository()
                val propertySet = repository.get(propertySetId)!!
                val propertySetInfo = ItemFactory.loadPropertySetInfo(propertySet)

                withContext(Dispatchers.Main) { setPackageCode(null) }
                selectItem(item.item, propertySetInfo, item.description, null)
            }
        }

        val action = ItemRegistrationPagerHolderDirections.actionNavItemRegistrationToNavStockItemDetails(ParcelUuid(item.item.id), true)
        findNavController().navigate(action)
    }

片段 A 和 B 都在一个独立的动态特性中。我唯一遇到的问题是当调用以下函数时:

fun onSelect() {

        viewModel.pickedLocation.value = (viewModel.selectedLocation as? LocationExt2?)?.location
        val result = bundleOf(Pair(LOCATION_ID, ParcelUuid(viewModel.pickedLocation.value!!.id)))
        setFragmentResult(REQUEST_LOCATION_KEY, result)
        findNavController().popBackStack()
    }

setFragmentResult(REQUEST_LOCATION_KEY, result)

这段代码没有产生任何结果,因为FragmentManager不是调用片段的同一个。在片段A中使用相同的方法:

private fun onSetSelected(id: UUID) {

    propertySets.removeObservers(viewLifecycleOwner)
    adapter.tracker = null
    setFragmentResult(SELECTED_ITEM_KEY, bundleOf(Pair(SELECTED_ITEM_SET_ID, ParcelUuid(id))))
    findNavController().popBackStack()
}

作为一个临时解决方案,我用 Activity.supportFragmentManager.setFragmentResultListener 替换了对 Fragment 的 FragmentManager 的调用。虽然它能工作,但我仍不明白为什么 A 和 B Fragment 表现不同。

2个回答

4

要检查侦听片段结果的片段和设置结果的片段是否在同一片段管理器中。

可能出现这种情况的常见情况是,如果您正在使用 Activity.getSupportFragmentManager() Fragment.getParentFragmentManager()以及 Fragment.getChildFragmentManager()


如何检查它们是否在同一个片段管理器中?我应该调用哪个API? - George Shalvashvili

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接