Se puede crear un fragmento con una sola instancia

Me preguntaba, puede fragmentar la creación sólo tiene una instancia o singleton?
Fui a través de Google iosched proyecto también. Simplemente crean

Fragment a = new Fragment(); 

Cuando quieran …

Supongamos, por ejemplo:

 public static FragmentManager instance; public static FragmentManager getInstance() { if (instance == null) { instance = new FragmentManager(); } return instance; } public TestFragment getTestFragment() { if (testFragment == null) { testFragment = new TestFragment (); } return testFragment } } 

¿Puedo usar FragmentManager.getInstance().getTestFragment() para la transacción?

p.ej:

 getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, FragmentManager.getInstance().getTestFragment()) .commit(); 

¿O el sistema operativo destruye automáticamente la referencia o algunos problemas relacionados con ella?

Cuando se utiliza getSupportFragmentManager().beginTransaction().replace se puede agregar un tercer parámetro como una cadena que se puede utilizar como una etiqueta, por lo que en caso de que quiera recuperar un fragmento anterior puede utilizar getSupportFragmentManager().findFragmentByTag(String) Por lo que no tendrá que crear un nuevo fragmento.

Así sería como esto

Compruebe si el fragmento existe usando findFragmentByTag(String) si no existe, cree un nuevo fragmento y llame a getSupportFragmentManager().beginTransaction() .replace(R.id.content_frame,myFragment,myTag).commit(); Donde myTag es la cadena que utilizará en su findFragmentByTag. De esta manera no creará más de un fragmento de cada tipo.

Espero que tenga sentido 🙂

Para más información ver esto y este

No hay tal limitación. Sin embargo, dos fragmentos de objetos no deben tener la misma etiqueta o id.

Además, es bueno volver a conectar un fragmento existente, en lugar de crear uno nuevo.

 MyFragment f = (MyFragment) getFragmentManager().findFragmenByTag("my_fragment"); if(f == null){ f = Fragment.instantiate(context, MyFragment.class.getName()); } if(!f.isAdded()){ //--do a fragment transaction to add fragment to activity, WITH UNIQUE TAG-- //--Optionally, add this transaction to back-stack as well-- } 

Si intenta asegurarse de que no agregará o reemplazará uno o más de sus fragmentos con el mismo "tipo" dos veces o más, puede utilizar FragmentManager.BackStackEntry para saber cuál de sus fragmentos se encuentra actualmente en la parte superior de la pila.

 String TAG_FIRST_FRAGMENT = "com.example.name.FIRST.tag"; String TAG_SECOND_FRAGMENT = "com.example.name.SECOND.tag"; FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() == 0 || !fragmentManager.getBackStackEntryAt( fragmentManager.getBackStackEntryCount() - 1) .getName().equals(TAG_SECOND_FRAGMENT)) { //Now it's safe to add the secondFragment instance FragmentTransaction transaction = fragmentManager.beginTransaction(); //Hide the first fragment if you're sure this is the one on top of the stack transaction.hide(getSupportFragmentManager().findFragmentByTag(TAG_FIRST_FRAGMENT)); SecondFragment secondFragment = new SecondFragment(); transaction.add(R.id.content_frame, secondFragment, TAG_SECOND_FRAGMENT); //Add it to back stack so that you can press back once to return to the FirstFragment, and //to make sure not to add it more than once. transaction.addToBackStack(TAG_SECOND_FRAGMENT); transaction.commit(); } 
  • Cómo encontrar listview en 'fragmento'
  • Android: El nuevo método getContext () de Fragment es qué contexto?
  • Multi-Pane fragmentos dentro de viewpager
  • Ciclo de vida del fragmento con respecto a su actividad
  • ¿Por qué FragmentManager getBackStackEntryCount () devuelve cero?
  • Android: la pantalla del fragmento gira
  • Fragmenttabhost rendimiento es lento?
  • Fragmento todavía existe después de quitar?
  • ¿Cómo mover el layoutFragment cuando el teclado suave se muestra en android?
  • No se puede actualizar fragmentos de texto al cambiar las tarjetas
  • Cómo ocultar el divisor entre las preferencias en el fragmento
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.