当用户点击每个行项目中的溢出图像时,我有以下代码显示弹出菜单。不幸的是我不知道如何将上下文传递给片段,导致onClick()没有得到上下文值。如果我直接在适配器类的getView()中创建了监听器,我设法显示弹出菜单但是如果我将监听器传递给片段,我就无法获得预期的结果。我可以知道如何调整下面的代码吗?
我目前的编码如下:
public class SubProductCustomAdapter extends BaseAdapter {
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//RecyclerView (Android 5.0) - To avoid app crash when there are too many records when user scroll
ViewHolder viewHolder;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//First Created
if(convertView == null )
{
convertView = mInflater.inflate(R.layout.item_sub_product, null);
viewHolder = new ViewHolder();
viewHolder.sub_product_name = (TextView)convertView.findViewById(R.id.txt_pdt_name);
viewHolder.popup_menu = (ImageView) convertView.findViewById(R.id.product_overflow);
SubRowProducts subRowPro = subRowProducts.get(position);
viewHolder.sub_product_name.setText(subRowPro.getSub_product_name());
//Managed to display popup menu using below method
/*viewHolder.popup_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context,v);
popupMenu.getMenuInflater().inflate(R.menu.drawermenu, popupMenu.getMenu());
popupMenu.show();
}
});*/
//Not managed to display popup menu using below method
viewHolder.popup_menu.setOnClickListener(new MySubProductListFragment());
//Store object inside convert view
convertView.setTag(viewHolder);
}
else{
//Reused or recycle the convertView
viewHolder = (ViewHolder)convertView.getTag();
}
//viewHolder.sub_product_name.setText(subRowProducts.get(position).getSub_product_name());
return convertView;
}
************************************************************************************************************
public class MySubProductListFragment extends ListFragment implements View.OnClickListener {
...
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(getActivity(),v);
popupMenu.getMenuInflater().inflate(R.menu.drawermenu, popupMenu.getMenu());
popupMenu.show();
}
}
答案 0 :(得分:1)
this
作为参数传递给适配器类构造函数。