android - 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.
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
解决方案
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.
推荐阅读
- elasticsearch - Elasticsearch geo_shape 点搜索返回错误的geometrycollection 文档
- python-3.x - 更新较新 Pytorch 的代码并获取 RuntimeError: Tensors must have same number of dimensions: got 2 and 1
- html - 如何从液体标签中写入有效的 HTML?
- reactjs - 如何传递属性,使用下一个 JS?
- sql - MS Access:确定 4 列中的第二高值
- composer-php - Swiftmailer“基本用法”导致未捕获的 ArgumentCountError:参数太少
- python - cv2.imshow() 无法正确显示图像
- python - 用于 Python 的 MySQL 连接器抛出“在查询期间丢失与 MySQL 服务器的连接”
- c# - 将 C# Blazor 应用程序部署到 AzureWebSites,但索引是常规 HTML 页面
- html - 为什么我的 Materialize Select 不起作用,即使我复制了代码?