从Fragment到Adapter Class的Android Pass值

时间:2016-01-13 09:04:50

标签: android fragment popupmenu

当用户点击每个行项目中的溢出图像时,我有以下代码显示弹出菜单。不幸的是我不知道如何将上下文传递给片段,导致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();

}

}

1 个答案:

答案 0 :(得分:1)

  1. 使用所需方法在适配器类中定义接口。
  2. 有一个适配器构造函数,需要该接口的引用
  3. 现在让你的ListFragment类实现适配器的接口,当你为适配器类创建引用时,将this作为参数传递给适配器类构造函数。
  4. 从适配器类构造函数有一个片段的私有引用,并调用你想要的任何方法。