Fragmento de ciclo de vida: onCreateView () no se llama cuando se utiliza el botón Volver

EDIT : después de alguna experimentación, parece que funciona como se espera si no agrego el fragmento inicial en el diseño xml. Ahora lo estoy haciendo en mi código fuente de actividad. Supongo que esto es lo que se esperaba que lo haga?

De acuerdo con http://developer.android.com/guide/components/fragments.html#Creating , si se elimina un fragmento y se agrega de nuevo, se debe llamar onCreateView ().

También puedo ver que getView () devuelve null. OnDestroyView () se llama, pero la interfaz de mi primer fragmento todavía se muestra cuando se pulsa de nuevo

Aquí está el resultado de mi código de ejemplo:

--launch app I/System.out( 3765): ==== FRAGMENT1.ONCREATE I/System.out( 3765): ==== FRAGMENT1.ONCREATEVIEW I/System.out( 3765): ==== FRAGMENT1.ONACTIVITYCREATED (FRAGMENT1.getView = android.support.v4.app.NoSaveStateFrameLayout@41301268 --second fragment I/System.out( 3765): ==== FRAGMENT2.ONCREATE I/System.out( 3765): ==== FRAGMENT2.ONCREATEVIEW I/System.out( 3765): ==== FRAGMENT2.ONACTIVITYCREATED --back is pressed : getView() == null and onCreateView is not called I/System.out( 3765): ==== FRAGMENT1.ONACTIVITYCREATED (FRAGMENT1.getView = null 

En caso de que esté haciendo algo mal, he aquí un código básico para reproducir mi problema:

Mis 2 clases de fragmentos:

 package com.test.testbackfragment; import android.support.v4.app.Fragment; import android.view.ViewGroup; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; public class Fragment1 extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { System.out.println("==== FRAGMENT1.ONCREATE"); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("==== FRAGMENT1.ONCREATEVIEW"); View v = inflater.inflate(R.layout.fragment1, container, false); v.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getActivity().getSupportFragmentManager().beginTransaction() .remove(Fragment1.this) .add(R.id.fragment, new Fragment2()) .addToBackStack(null) .commit(); } }); return v; } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); System.out.println("==== FRAGMENT1.ONACTIVITYCREATED (FRAGMENT1.getView = "+getView()); } } 

y

 package com.test.testbackfragment; import android.support.v4.app.Fragment; import android.view.ViewGroup; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; public class Fragment2 extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { System.out.println("==== FRAGMENT2.ONCREATE"); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("==== FRAGMENT2.ONCREATEVIEW"); View v = inflater.inflate(R.layout.fragment2, container, false); return v; } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); System.out.println("==== FRAGMENT2.ONACTIVITYCREATED"); } } 

La actividad principal es muy simple

 package com.test.testbackfragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 

Y aquí están los 3 diseños: main.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:name="com.test.testbackfragment.Fragment1" android:id="@+id/fragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> 

Fragment1.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#0000FF"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20dip" android:text="THIS IS FRAGMENT1" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20dip" android:text="FRAGMENT2"/> </LinearLayout> 

Fragment2.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00FF00"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20dip" android:text="THIS IS FRAGMENT2" /> </LinearLayout> 

Cuando el sistema crea este diseño main.xml, instancia fragmento especificado en el diseño y llama al método onCreateView () para recuperar el diseño de cada fragmento. Posteriormente utilizará instancias del mismo fragmento. Por lo tanto, no volverá a llamar a OnCreateView.

Si desea crear de nuevo, obtenga una instancia de FragmentTransaction de su actividad e implemente como desee.

 FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction .replace(R.id.fragment, newFragment); // Commit the transaction transaction.commit(); 

Intente eliminar el fragmento de la pila de FragmentManager utilizando FragmentTransaction.remove(your fragment) antes del evento BackPress .

O simplemente utilizar el FragmentTransaction.replace() para cargar el nuevo fragmento.

  • Cómo implementar OnFragmentInteractionListener
  • Los elementos de la barra de acciones de Android permanecen al estallar el fragmento
  • Solución para el error de Android relacionado con setRetainInstance (true)
  • Uso de `onPrepareOptionsMenu ()` en Android 3.0+
  • Android Honeycomb: Fragmento no puede iniciar AsyncTask?
  • Cómo cambiar el estilo de texto en el fragmento de preferencia
  • Cómo utilizar el tipo de llamada con EventBus
  • ¿Cómo reemplazar el fragmento C con el fragmento A cuando se pulsa el botón Atrás?
  • ¿Cómo ocultar el teclado suave desde el interior de un fragmento?
  • Llamar el show de DialogFragment () desde dentro onRequestPermissionsResult () provoca IllegalStateException en Marshmallow
  • Android reemplaza fragmento o inicia nueva actividad con fragmento
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.