public class MyRecyclerViewextends RecyclerView {
private MyRecyclerViewContextMenuInfomyRecyclerViewContextMenuInfo;
public MyRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean showContextMenuForChild(View originalView) {
//获得myRecyclerViewContextMenuInfo 对象
int position = getChildViewHolder(originalView).getBindingAdapterPosition();
if (position >=0) {
myRecyclerViewContextMenuInfo =new MyRecyclerViewContextMenuInfo(position);
return super.showContextMenuForChild(originalView);
}
return false;
}
//返回ContextMenuInfo
@Override
protected ContextMenu.ContextMenuInfogetContextMenuInfo() {
return myRecyclerViewContextMenuInfo;
}
@Override
public ViewHoldergetChildViewHolder(View child) {
return super.getChildViewHolder(child);
}
public static class MyRecyclerViewContextMenuInfoimplements ContextMenu.ContextMenuInfo {
public int position;
public MyRecyclerViewContextMenuInfo(int position) {
this.position = position;
}
}
recyclerView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.add(0,1,0,"删除");
//获得位置
itemPosition = ((MyRecyclerView.MyRecyclerViewContextMenuInfo)contextMenuInfo).position;
}
});