2016-01-13 72 views
0

我有下面的代碼來顯示彈出式菜單,當用戶單擊每個行項目中的溢出圖像時。不幸的是,我不知道如何將上下文傳遞給導致onClick()沒有獲取上下文值的片段。我設法顯示彈出式菜單,如果我直接在適配器類的getView()中創建監聽器,但我不能得到預期的結果,如果我將偵聽器傳遞給片段。我可以知道如何適應我的代碼?從片段到適配器類的Android傳遞值

我現在的編碼是如下:

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
  1. 定義一個接口,適配器類所需的方法。
  2. 有一個適配器的構造,其預計該接口的參考
  3. 現在讓你ListFragment類實現適配器的接口,當你創建你的適配器類通this作爲參數傳遞給適配器類的構造函數的引用。
  4. 從適配器類的構造函數有一個片段的私人引用,並調用你想要的任何方法。
相關問題