如何使用 MVVM 模型在 Fragment 中显示 Toast 消息

How to show a Toast message in a Fragment using MVVM model

我正在尝试使用 MutableLiveData 事件在 Fragment 中显示 Toast 消息,但我无法显示 Toast 消息,错误是

None of the following functions can be called with the arguments supplied. makeText(Context!, CharSequence!, Int) defined in android.widget.Toast makeText(Context!, Int, Int) defined in android.widget.Toast

视图模型

class AddProductViewModel (
    private val repository: ProductRepository,
    private val context: Context
): ViewModel(), Observable {

    private  val statusMessage = MutableLiveData<Event<String>>()

    val message : LiveData<Event<String>>
        get() = statusMessage

}

片段

class AddProductFragment: Fragment() {
    private lateinit var binding: AddProductBinding
    private lateinit var addProductViewModel: AddProductViewModel
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =  DataBindingUtil.inflate(inflater, R.layout.add_product, container, false)
        val dao = SubscriberDatabase.getInstance(requireActivity().applicationContext).productDAO
        val repository = ProductRepository(dao)
        val factory = AddProductViewModelFactory(repository, requireActivity().applicationContext)
        addProductViewModel = ViewModelProvider(this, factory).get(AddProductViewModel::class.java)
        binding.addProductViewModel = addProductViewModel
        binding.lifecycleOwner = this
        val view = binding.root

        addProductViewModel.message.observe(viewLifecycleOwner, Observer {
            it.getContentIfNotHandled()?.let {
                ***Error is on this line***
                Toast.makeText(viewLifecycleOwner,it, Toast.LENGTH_LONG).show
            }
        })

        return view
    }
}

我该如何更正此问题,请提前致谢

谢谢 R

请使用下一行在 Fragment 中显示 Toast 消息:

 Toast.makeText(context, it, Toast.LENGTH_LONG).show()

您使用 viewLifecycleOwner 作为第一个参数,但它应该是 Context