简体   繁体   English

我们怎样才能实现Fragment和Activity之间的共享视图Model通信,其中Activity不是Parent

[英]How can we achieve Shared View Model communication between a Fragment and Activity, where the Activity is not the Parent

I am trying to achieve Fragment to Activity communication given that the Activity is not the parent Activity.鉴于 Activity 不是父 Activity,我正在尝试实现 Fragment 到 Activity 的通信。

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.所以,我有一个MainActivity有一个名为ContactListFragment的片段,当单击MainActivityBottomNavigationView上的添加按钮时,我正在打开另一个AddContactActivity来添加联系人。 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 .我的要求是当我单击AddContactActivity上的保存按钮时,我需要在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?我认为最好的方法是为此使用共享视图 Model,但在这种情况下,我应该如何创建视图 model 以便生命周期所有者不会改变?

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.我考虑过使用Application Context作为所有者,但我觉得它对于这样的任务来说有点过头了,而且当其他模块添加到项目中时,它可能会产生一些后果。

So is there a way to efficiently implement this approach?那么有没有办法有效地实施这种方法? Thanks.谢谢。

Write an interface class with object/objects/Data types you need to sync使用需要同步的对象/对象/数据类型编写接口 class

interface OnSaveClickListener {
    fun onSaveClicked(contact: Contact)
}

Now in ContactListFragment class现在在 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
    }
        
}

In AddContactActivity,在 AddContactActivity 中,

class AddContactActivity {
   var mOnSaveClickListener : OnSaveClickListener? = null

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM