Reputation: 87
I would like to like to ask you how I call a method in activity from adapter recycler view.
In function buildRecyclerView there is set up the adapter:
private void buildRecyclerView() {
offerAdapter = new OfferAdapter();
recyclerView.setAdapter(offerAdapter);
}
In class OfferAdapter.java
there is created submenu for each item and with onMenuItemClickListener
:
@Override
public void onBindViewHolder(NoteHolder holder, int position) {
PopupMenu popup = new PopupMenu(mCtx, holder.button);
popup.inflate(R.menu.menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
// TODO here I want to call delete item in MyOfferFragment.java
}
The main question: How I can call from *onMenuItemClickListnere*
the function in *MyOfferFragment*
.
Thank you very much in advance
Upvotes: 1
Views: 810
Reputation: 1968
You can pass a listener object in the constructor which implements by fragment OR activity
/**
* item click interface of adapter
*/
public interface OfferAdapterListener {
void onItemClick(int position)
}
This interface implent by fragment
/**
* On item clicked Implement Method from adapter listener.
*
* @param position
*/
@Override
public void onItemClick(int position) {
// Here you can call that method
}
then you pass this listener in the constructor of the adapter.
private void buildRecyclerView() {
offerAdapter = new OfferAdapter(this);
recyclerView.setAdapter(offerAdapter);
}
In the constructor, you can assign like this
private OfferAdapterListener mOfferAdapterListener;
public OfferAdapter(OfferAdapterListener mOfferAdapterListener) {
this.mOfferAdapterListener = mOfferAdapterListener
}
}
Now you can use this listener by setting click listener on anyViwe like this
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mOfferAdapterListener.onItemClick(position);
}
});
It returns to call the method of onItemClick which implements this method.
OR
You can pass activity or fragment context in the constructor like above and call it through by it reference like this
((MainActivity) mActivity).methodName(arguments);
Here is mActivity
reference context which you pass through in constructor.
Upvotes: 3
Reputation: 11
You can add the MyOfferFragment
to your adapter constructor.
private void buildRecyclerView() {
offerAdapter = new OfferAdapter(this); // Adding fragment to constructor
recyclerView.setAdapter(offerAdapter);
}
In OfferAdapter.java
:
private MyOfferFragment mFragment; // field variable
OfferAdapter (MyOfferFragment fragment){
mFragment = fragment;
}
You can then access MyOfferFragment
methods via mFragment
:
mFragment.deleteItem();
However, I think it is a more conventional way to just move methods related to RecyclerView into the adapter if possible. You can refer to this if you want to delete an item from RecyclerView: Android RecyclerView addition & removal of items
Upvotes: 1