首页 > 解决方案 > Option menu in recycler view adapter

问题描述

I would like to like to ask you how I call a method in activity from adapter recycler view.

enter image description here

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

标签: androidandroid-recyclerview

解决方案


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.


推荐阅读