简体   繁体   中英

get result from activity in adapter

In my fragment I have a recycler view and set adapter to it. With adapter's help I can start start second activity by clicking on items in recycler view. But when I finish second activity I need to call one method again in my fragment. I can start activityForResult only in adapter, but I write onActivityResult method in it.

How can I get result from the activity or call method in fragment again? Is it possible to get result from activity in adapter?

In general, the Adapter should only care about creating RecyclerView cells. Any other logic is better put elsewhere (Activity/Fragment, or better - ViewModel/Presenter)

In case you don't have a view model per RecyclerView cell, I would use an interface to let the Fragment know that an item was clicked:

public interface ItemClickedListener {
    fun itemClicked(String itemName)
}

In your Adapter:


public class YourAdapter(private val listener: ItemClickedListener): RecyclerView.Adapter<ViewHolder> {

}

In your Fragment (where you create your Adapter) pass "this" as the ItemClickedListener:

adapter = YourAdapter(this)

Have your Fragment implement ItemClickedListener & onActivityResult:

public class YourFragment: Fragment, ItemClickedListener {

 
    override fun itemClicked(String itemName) {
        startActivityForResult(...)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // Let your adapter know whatever is needed
    }

}

Back in your Adapter, instead of calling startActivityForResult upon item click - call listener.itemClicked

This is a basic example of removing the navigation logic from the Adapter.
Now the Fragment is making decisions about navigation, which might be OK if no business logic is involved. For cases where more business logic is needed, a better paradigm should be used (MVP, MVVM, MVI, etc..).
As Android recommends using MVVM, I would advice you to read this: https://developer.android.com/topic/architecture

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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