我有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 传递SearchFragment
给DialogFragment
. 我有这个代码用于我的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