Search code examples
androidandroid-activityandroid-recyclerviewfragment

how to access items in RecyclerView in fragment from an activity


I have an activity that has a TabLayout(where my Fragments are in) and myFragment has a RecyclerView itself.
I want to show every touched Item's name in a textView in myActicvity.

This is an image that explains my problem.

enter image description here

How should I do that? Thanks for any Help!.


Solution

  • You can use Event bus: https://github.com/greenrobot/EventBus. This library help you to send events from one activity/fragment/view to another. You must just add onclicklistener for item root element, and do something like this: EventBus.getDefault().post(getItemName());. And at your activty add this:

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(String name) {
       textView.setText(name);
    };
    

    And don't forget to register and unregister listener.