2017-07-26 131 views
1

我需要在用戶點擊recyclerview項目時打開一個新片段。從RecyclerViewAdapter打開片段

我使用下面的代碼:

@Override 
public boolean onMenuItemClick(MenuItem menuItem) { 
    switch (menuItem.getItemId()) { 
     case R.id.action_favourite: 




      mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); 


      SharedPreferences.Editor editor = mPref.edit(); 
      Log.d("HOLA PERFIL", "HE PULSADO EL PRODUCTO: " + tiendas.get(pos).getId_producto()); 


      editor.putInt("ID_PRODUCTO", tiendas.get(pos).getId_producto()); 
      editor.putString("NOMBRE_PRODUCTO", tiendas.get(pos).getNombre_producto()); 
      editor.putString("DESCRIPCION_PRODUCTO", tiendas.get(pos).getDescripcion_producto()); 
      editor.putString("PRESENTACION_PRODUCTO", tiendas.get(pos).getPresentacion_producto()); 
      editor.putString("PRECIO_PRODUCTO", tiendas.get(pos).getPrecio_producto()); 
      editor.putString("ESPECIFICACIONES_PRODUCTO", tiendas.get(pos).getEspecificaciones_producto()); 
      editor.putString("IMAGEN_PRODUCTO", tiendas.get(pos).getImagen_producto()); 
      editor.apply(); 


      DetalleTiendaFragment firstFragment = new DetalleTiendaFragment(); 
      ((MainActivity)context).getSupportFragmentManager().beginTransaction() 
        .add(R.id.frame, firstFragment); 




      return true; 

     default: 
    } 
    return false; 
} 

我使用在其他項目上相同的動作,它工作正常,但在這裏它doesn't打開片段,並沒有警告或錯誤被拋出:

DetalleTiendaFragment firstFragment = new DetalleTiendaFragment(); 
        ((MainActivity)context).getSupportFragmentManager().beginTransaction() 
          .add(R.id.frame, firstFragment); 
+0

beginTransaction().... commit(); – matoni

+0

@matoni,你是什麼意思? – mvasco

+1

我想,片段不顯示的原因是你忘記調用commit();.標準流程是:getSupportFragmentManager()。beginTransaction()。add(...)。commit(); – matoni

回答

1

改變此密碼

DetalleTiendaFragment firstFragment = new DetalleTiendaFragment(); 
      ((MainActivity)context).getSupportFragmentManager().beginTransaction() 
        .add(R.id.frame, firstFragment); 

要將此代碼

DetalleTiendaFragment firstFragment = new DetalleTiendaFragment(); 
FragmentTransaction transaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction(); 
transaction.replace(R.id.frame, firstFragment); 
transaction.addToBackStack("firstFragment"); 
transaction.commit(); 
+0

謝謝,它現在有效 – mvasco

+0

沒問題。 :)高興地幫助你。 – UmarZaii