Obtener el objeto fragmento actual


En mi main.xml tengo{[17]]}

  <FrameLayout
        android:id="@+id/frameTitle"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="@drawable/title_bg">
            <fragment
              android:name="com.fragment.TitleFragment"
              android:id="@+id/fragmentTag"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" />

  </FrameLayout>

Y estoy estableciendo el objeto fragmento como este

FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");

// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Está configurando diferentes tipos de objetos de fragmento (FragmentType2,FragmentType3,...) en diferentes momentos. Ahora en algún momento necesito identificar qué objeto está actualmente allí.

{[16] {} En[23]}corto necesito hacer algo como esto:
Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle

He intentado lo siguiente

TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);

Y

    TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");

Pero ambos objetos (titleFragmentById y titleFragmentByTag ) son null
¿Me he perdido algo?
Estoy usando Compatibility Package, r3 y desarrollando para API level 7.

findFragmentById() y findFragmentByTag() funcionará si hemos establecido fragment usando fragmentTransaction.replace o fragmentTransaction.add, pero lo hará return null si hemos establecido el objeto en xml (como lo que he hecho en mi main.xml). Creo que me falta algo en mis archivos XML.

Author: Léo Lam, 2011-07-19

13 answers

Ahora en algún momento necesito identificar qué objeto está actualmente allí

Llama a findFragmentById() en FragmentManager y determina qué fragmento está en tu contenedor R.id.frameTitle.

 237
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-19 17:39:29

Prueba esto,

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);

Esto le dará a u el fragmento actual, luego puede compararlo con la clase fragment y hacer sus cosas.

    if (currentFragment instanceof NameOfYourFragmentClass) {
     Log.v(TAG, "find the current fragment");
  }
 87
Author: Hammer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-15 15:28:35

Creo que puede usar onAttachFragment el evento puede ser útil para detectar qué fragmento está activo.

@Override
public void onAttachFragment(Fragment fragment) {
    // TODO Auto-generated method stub
    super.onAttachFragment(fragment);

    Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();

}
 35
Author: Hede Hodo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-24 03:24:44

Creo que deberías hacer:

Fragment currentFragment = fragmentManager.findFragmentByTag("fragmentTag");

La razón es porque establece la etiqueta "fragmentTag" al último fragmento que ha agregado (cuando llamó reemplazar).

 11
Author: Niqo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-25 05:14:31

Esta es la solución más simple y funciona para mí.

1.) agregas tu fragmento

ft.replace(R.id.container_layout, fragment_name, "fragment_tag").commit();

2.)

FragmentManager fragmentManager = getSupportFragmentManager();

Fragment currentFragment = fragmentManager.findFragmentById(R.id.container_layout);

if(currentFragment.getTag().equals("fragment_tag"))

{

 //Do something

}

else

{

//Do something

}
 9
Author: Gau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 08:44:30

Puede ser tarde, pero espero que ayude a alguien más, también @CommonsWare ha publicado la respuesta correcta.

FragmentManager fm = getSupportFragmentManager();
Fragment fragment_byID = fm.findFragmentById(R.id.fragment_id);
//OR
Fragment fragment_byTag = fm.findFragmentByTag("fragment_tag");
 8
Author: Ahmad Ali Nasir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-19 17:44:59

Puede obtener la lista de los fragmentos y mirar el último.

    FragmentManager fm = getSupportFragmentManager();
    List<Fragment> fragments = fm.getFragments();
    Fragment lastFragment = fragments.get(fragments.size() - 1);

Pero a veces (cuando navega hacia atrás) el tamaño de la lista permanece igual, pero algunos de los últimos elementos son null. Así que en la lista iteré al último fragmento no nulo y lo usé.

    FragmentManager fm = getSupportFragmentManager();
    if (fm != null) {
        List<Fragment> fragments = fm.getFragments();
        for(int i = fragments.size() - 1; i >= 0; i--){
            Fragment fragment = fragments.get(i);
            if(fragment != null) {
                // found the current fragment

                // if you want to check for specific fragment class
                if(fragment instanceof YourFragmentClass) {
                    // do something
                }
                break;
            }
        }
    }
 8
Author: eluleci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-04 09:02:35

Tal vez la forma más simple es:

public MyFragment getVisibleFragment(){
    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    for(Fragment fragment : fragments){
        if(fragment != null && fragment.getUserVisibleHint())
            return (MyFragment)fragment;
    }
    return null;
}

Funcionó para mí

 6
Author: madx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-07 18:00:42

Sé que ha pasado un tiempo, pero voy a esto aquí en caso de que ayude a alguien.

La respuesta correcta por mucho es (y la seleccionada) la de CommonsWare. Yo estaba teniendo el mismo problema como publicado, el siguiente

MyFragmentClass fragmentList = 
            (MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);

Siguió devolviendo null. Mi error fue realmente tonto, en mi archivo xml:

<fragment
    android:tag="@+id/fragementID"
    android:name="com.sf.lidgit_android.content.MyFragmentClass"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

El error fue que tenía android:tag EN LUGAR DE android:id.

 4
Author: Chayemor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-11 21:04:19

Puede crear un campo en su clase de Actividad principal:

public class MainActivity extends AppCompatActivity {

    public Fragment fr;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

}

Y luego dentro de cada clase de fragmento:

public class SomeFragment extends Fragment {

@Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        ((MainActivity) getActivity()).fr = this;
}

Su campo 'fr' es Objeto de fragmento actual

También funciona con popBackStack ()

 3
Author: buxik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-08 11:26:16

Si está utilizando el BackStack...y SOLO si estás usando el back stack, entonces prueba esto:

rivate Fragment returnToPreviousFragment() {

    FragmentManager fm = getSupportFragmentManager();

    Fragment topFrag = null;

    int idx = fm.getBackStackEntryCount();
    if (idx > 1) {
        BackStackEntry entry = fm.getBackStackEntryAt(idx - 2);
        topFrag = fm.findFragmentByTag(entry.getName());
    }

    fm.popBackStack();

    return topFrag;
}
 2
Author: James Barwick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-10 04:45:08

@Hammer respuesta funcionó para mí, im usando para controlar un botón de acción flotante

final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
            Log.d("VIE",String.valueOf(currentFragment));
            if (currentFragment instanceof PerfilFragment) {
                PerfilEdit(view, fab);
            }
        }
});
 2
Author: Thiago Melo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 19:06:31

Si está definiendo el fragmento en el layour XML de la actividad, en el Activity asegúrese de llamar a setContentView() antes de llamar a findFragmentById().

 0
Author: IvancityM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-14 13:55:00