我有一个 Activity
称为 Homeactivity
我有一个 fragment Notification
和他们的ViewModel
类,我想从 fragment 的 ViewModel
更新通知计数我在通知之外声明了该接口(interface)ViewModel
而且我无法在 Kotlin 中调用该接口(interface)的方法
class NotificationsViewModel(val notificationsActivity: HomeActivity) :
BaseObservable() {
//somewhere i want to update count which is in homeactivity
}
interface NotifyCount {
fun notifyNotificationCount(count: String)
}
我的 fragment 类如下
class NotificationsFragment : Fragment() {
private var notificationsBinding: NotificationsActivityBinding? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
notificationsBinding= DataBindingUtil.inflate(inflater, R.layout.notifications_activity,container,false)
notificationsBinding!!.viewModel= NotificationsViewModel(activity!! as HomeActivity)
return notificationsBinding!!.root
}
}
我只想调用方法
notifyNotificationCount
在 ViewModel
这样我就会从 HomeActivity
更新我的计数通过覆盖 NotifyCount
如何调用方法
notifyNotificationCount
在View 模型类?
最佳答案
您可以使用 MutableLiveData
在您的 ViewModel 类中并观察通知计数的值,每当通知计数的值发生变化时,它都会通知观察类。
关于android - 如何在kotlin fragment 类的 View 模型中调用接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53260283/