0

我有SearchFragment以下代码。

@AndroidEntryPoint
class SearchFragment :
    Fragment(),
    View.OnClickListener {
    ...
    private var _binding: FragSearchBinding? = null
    private val binding get() = _binding as FragSearchBinding
    private val viewmodel by viewModels<SearchViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    )
        : View {
        _binding = FragSearchBinding.inflate(inflater, container, false)
        binding.fragSearchSearchResultFilter.setOnClickListener(this)
        return binding.root
    }

    ...

    private fun showFilterDialog() {
        val dialog = FilterBottomSheetDialogFragment.newInstance()
        dialog.show(parentFragmentManager, "filter_bsd_tag")
    }
    ...
}

我正在展示FilterBottomSheetDialogFragment使用它SearchFragment。我想将 ViewModel 传递SearchFragmentDialogFragment. 我有这个代码用于我的FilterBottomSheetDialogFragment.

@AndroidEntryPoint
class FilterBottomSheetDialogFragment :
    BottomSheetDialogFragment(),
    View.OnClickListener {
    companion object {
        fun newInstance() = FilterBottomSheetDialogFragment()
        private const val TAG_SELECTION_DIALOG = "tag_selection_dialog"
    }

    private var _binding: BsdFilterBinding? = null
    private val binding get() = _binding as BsdFilterBinding
    private val viewmodel: SearchViewModel = ???
}

我试过了

private val viewmodel by viewModels<SearchViewModel>(ownerProducer = { this.requireParentFragment() })

以上不起作用,因为它只是创建了一个新的 ViewModel 实例。

我也试过

private val viewmodel: SearchViewModel by lazy {
    ViewModelProvider(requireParentFragment()).get(SearchViewModel::class.java)
}

以上不适用于SearchViewModel无法创建实例的错误。我SearchViewModel有这个构造函数。

@HiltViewModel
class SearchViewModel @Inject constructor(
    private val courseRepository: CourseRepository
) : ViewModel()

如何在不使用构造函数参数的情况下将 传递SearchViewModel给?DialogFragment

4

1 回答 1

3

您在这里弄错了,实际上是您在显示对话框时使用的片段管理器。目前您正在使用片段管理器,而您的对话框应该作为显示它的片段的子片段存在。

所以你应该使用:

dialog.show(childFragmentManager, "filter_bsd_tag")

这将确保

viewModels<SearchViewModel>(ownerProducer = { requireParentFragment() })

指的是SearchFragment

于 2021-04-24T16:25:25.767 回答