Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

android - 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.

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?

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.

question from:https://stackoverflow.com/questions/65932555/how-can-we-achieve-shared-view-model-communication-between-a-fragment-and-activi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

interface OnSaveClickListener {
    fun onSaveClicked(contact: Contact)
}

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
    }
        
}

In AddContactActivity,

class AddContactActivity {
   var mOnSaveClickListener : OnSaveClickListener? = null

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...