android - 如何在kotlin fragment 类的 View 模型中调用接口(interface)方法

标签 android kotlin interface viewmodel

我有一个 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
}

}

我只想调用方法notifyNotificationCountViewModel这样我就会从 HomeActivity 更新我的计数通过覆盖 NotifyCount
如何调用方法notifyNotificationCount
View 模型类?

最佳答案

您可以使用 MutableLiveData在您的 ViewModel 类中并观察通知计数的值,每当通知计数的值发生变化时,它都会通知观察类。

关于android - 如何在kotlin fragment 类的 View 模型中调用接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53260283/

相关文章:

android - Adobe AIR for Android - 打开 native Facebook 应用程序

android - 操作输入法设置后返回 Activity

java - 接口(interface)的默认实现?或保留为空

python - 如何在程序中添加转换屏幕?

java - 定义自己的XMLEventReader来实现Closeable接口(interface)

android - 如何克隆 View 对象以便将其添加到当前 View 层次结构中

以编程方式连接Android WiFi

kotlin - 在 iOS/XCode 的内置 .frameworks 中包含 Kotlin/Native KDocs 文档

android - 警报对话框不适应暗模式和非暗模式

android - 无法解析 : androidx. 生命周期 :lifecycle-extensions-ktx:2. 0.0-alpha1