简体   繁体   中英

How do I call a method in a adapter who is initialized in a fragment that is contained in an Activity?

Im trying to use a button in my recycleviewers on click to run a method that is in my Main Activity. This recyleview is intialized in a fragment that is nested in that Activity.

So it goes:

MainActivity - > Fragment -> RecycleViewAdapter

How can RecycleviewAdapter call a method from MainActivity?

Option 1: Create an interface in the Activity . Pass it to the Fragment , then to the Adapter .

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if(context instanceof YouInterface){
        listener = (YourInterface)context;
    } 
}

Then pass the listener in the Adapter s constructor

Option 2: BroadcastReceiver / EventBus

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