Jon-ElCapitan
Jon-ElCapitan

Reputation: 67

Android Call a method from adapter

I have a method in a fragment that I want to call when user clicks a recyclerview item. For example

holder.addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //call the method in fragment
                //e.g.  activity instance context dot(.) method name
                mainActivity.refreshData();
            }
   }

In main activity it will be simple as

public void refreshData(){
     // refresh
}

Upvotes: 0

Views: 667

Answers (2)

ahmad bajwa
ahmad bajwa

Reputation: 1068

This function is in your main-class:

    public void refreshData(){
     // refresh
}

Now can Call that function in your adapter by this.

holder.addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //call the method in fragment
                //e.g.  activity instance context dot(.) method name
             ((MainActivity) Objects.requireNonNull(context)).refreshData();
            }
   }

Note: you need to pass the fragment context to your adapter. Here is the exmaple code how I passed the context from main-class to fragment then fragment to the adapter.

Context context;
   public ProfileFragment(Context context) {
        this.context = context;
    }
  adapter = new ProfileTimelineAdapter(context, modelFeedArrayList);

Upvotes: 1

shmakova
shmakova

Reputation: 6426

Create an interface of a click listener:

interface ItemClickListener {
    void onItemClick();
}

Add this listener to your RecyclerView adapter's constructor:

private final ItemClickListener itemClickListener;

public MyAdapter(ItemClickListener itemClickListener) {
    this.itemClickListener = itemClickListener;
}

And add there the click listener for your addButton:

holder.addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        itemClickListener.onItemClick();
    }
}

Pass the implementation of ItemClickListener interface to your adapter in your activity class, for example like this:

MyAdapter adapter = new MyAdapter(() -> refreshData());

Upvotes: 2

Related Questions