如何在Kotlin的片段类视图模型中调用接口方法

时间:2018-11-12 10:32:20

标签: android kotlin interface viewmodel

我有一个Activity,称为Homeactivity,我有一个片段Notification及其ViewModel类,我想从片段的{{1}更新通知计数},并且在通知ViewModel之外声明了该接口,但无法在Kotlin中调用该接口的方法

ViewModel

我的片段类在下面给出

class NotificationsViewModel(val notificationsActivity: HomeActivity) : 
          BaseObservable() {  


 //somewhere i want to update count which is in homeactivity

    } 
  interface NotifyCount {
    fun notifyNotificationCount(count: String)

}

我只想在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 viewModel`类?

1 个答案:

答案 0 :(得分:0)

您可以在ViewModel类中使用MutableLiveData并观察通知计数的值,只要通知计数的值更改,它就会通知您观察该类。