我们如何实现片段与活动之间的共享视图模型通信,其中活动不是父级 [英] How can we achieve Shared View Model communication between a Fragment and Activity, where the Activity is not the Parent

查看:46
本文介绍了我们如何实现片段与活动之间的共享视图模型通信,其中活动不是父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于活动不是父活动,我正在尝试实现片段到活动"的通信.

I am trying to achieve Fragment to Activity communication given that the Activity is not the parent Activity.

因此,我有一个 MainActivity ,其中有一个名为 ContactListFragment 的片段,而 MainActivity 被单击,我打开另一个 AddContactActivity 来添加联系人.我的要求是,当我单击 AddContactActivity 上的保存按钮时,我需要在 ContactListFragment 中启动与服务器的数据同步.我认为最好的方法是为此使用共享视图模型,但是在那种情况下,我应该如何创建视图模型,以便生命周期所有者不被更改?

So, I have a MainActivity that has a fragment called ContactListFragment, while the add button on the BottomNavigationView of MainActivity is clicked, I am opening another AddContactActivity to add a contact. My requirement is to when I am clicking the save button on the AddContactActivity, I need to initiate a data-sync with server in ContactListFragment. I think the best approach would be to use a Shared View Model for this, but in that Case how should I create the view model so that the lifecycle owner doesn't get changed?

我曾考虑过使用 Application Context 作为所有者,但是我觉得这对于这样的任务来说是过大的,当将其他模块添加到项目中时,它可能会产生一些后果.

I thought about using the Application Context as the owner but I feel like its an overkill for a task like this, and it may produce some consequences down the line when other modules are added to the project.

那么有没有一种方法可以有效地实现这种方法呢?谢谢.

So is there a way to efficiently implement this approach? Thanks.

推荐答案

用需要同步的对象/对象/数据类型编写一个接口类

Write an interface class with object/objects/Data types you need to sync

interface OnSaveClickListener {
    fun onSaveClicked(contact: Contact)
}

现在在ContactListFragment类中

Now in ContactListFragment class

class ContactListFragment : Fragment(), OnSaveClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (activity as AddContactACtivity).mOnSaveClickListener = this
    }

   
    override fun onSaveClicked(contact: Contact) {
        // Whatever you want to do with the data
    }
        
}

在AddContactActivity中,

In AddContactActivity,

class AddContactActivity {
   var mOnSaveClickListener : OnSaveClickListener? = null

   private void whenYouClickSave(contact: Contact){
       mOnSaveClickListener?.onSaveClicked(contact)
   }

这篇关于我们如何实现片段与活动之间的共享视图模型通信,其中活动不是父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆