android - studio - title html attribute
Uso adecuado de subgrupos con FragmentManager(hijo) (1)
Debe agregar SubFragment a Fragment la misma manera que agrega Fragment a Activity . Me refiero a que agregar Fragment a la Activity debería ser como:
@Override
public void onCreate(Bundle savedInstanceState) {
....
if (savedInstanceState == null){
//add fragment
mMainFragment = new MainFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_main, mMainFragment);
transaction.commit();
}
}
Agregar SubFragment a MainFragment debería verse así:
public class MainFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater i, ViewGroup c, Bundle savedInstanceState) {
...
if (savedInstanceState == null){
mSubFragment = new SubFragment();
//add child fragment
getChildFragmentManager()
.beginTransaction()
.add(R.id.fragment_sub, mSubFragment, "tag")
.commit();
}
}
}
o puede agregar un fragmento hijo a Fragment en el método onCreate
¿Cómo uso correctamente los fragmentos en fragmentos?
Mi caso de uso (simplificado) es el siguiente, tengo una actividad con un fragmento de diseño y este fragmento contiene un subgrupo ... todos los fragmentos se agregan manualmente a sus padres ...
----------------------------------------------------------
- Activity -
- -
- -
- --------------------------------------- -
- - Fragment - -
- - - -
- - ----------------- - -
- - - SubFragment - - -
- - - - - -
- - - - - -
- - ----------------- - -
- --------------------------------------- -
- -
----------------------------------------------------------
Ahora en mi actividad onCreate hago lo siguiente:
if (savedInstanceState == null)
{
// I create the fragment
mMainFragment = new MainFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_main, mMainFragment);
transaction.commit();
}
else
{
// I retrieve the fragment
mMainFragment = (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_main);
}
Y en mis fragmentos onCreate , obtengo / creo mi SubFragmento:
mSubFragment = getChildFragmentManager().findFragmentByTag(SubFragment.class.getName());
if (mSubFragment == null)
{
mSubFragment = new SubFragment();
getChildFragmentManager().beginTransaction().add(R.id.fragment_sub, mSubFragment, SubFragment.class.getName()).commit();
}
Problema
Después de la rotación de la pantalla, mi Subfragmento se agrega dos veces ... Si uso el FragmentManager la actividad, entonces funciona ... Pero, ¿por qué no funciona con el ChildFragmentManager ? Por supuesto, el Fragmento es un fragmento nuevo, pero la actividad también es nueva, así que ¿por qué funciona con el FragmentManager la actividad pero no con el fragmento principal?
En un fragmento, debería usar los fragmentos ChildFragmentManager , ¿no es así?