mvasco mvasco - 1 year ago 100
Android Question

Opening fragment from RecyclerViewAdapter

I need to open a new fragment when the user clicks on a recyclerview item.

I am using following code:

@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;
}


I am using the same action on other projects and it works fine, but here it doesn´t open the fragment, and no warning or error is thrown:

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

Answer Source

Change this code

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

To this code

DetalleTiendaFragment firstFragment = new DetalleTiendaFragment();   
FragmentTransaction transaction = ((MainActivity)context).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, firstFragment);
transaction.addToBackStack("firstFragment");
transaction.commit();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download