Pregunta

I have Activity A that contains Fragment F. In the xml file for Fragment F, I have a FrameLayout named "container". And in this container I load fragments X and Y whenever I need to.

Now, is there a way for me to determine which between X and Y is currently being displayed by Fragment F?

In Activity A, I want to implement

onBackPressed(){
    if(F is displaying X)
        super.onBackPressed();
    else //Y is currently displayed
        //replace fragment Y with fragment X

I think that I might need to call

    getSupportFragmentManager().findFragmentByTag("F"). ?? 

This is how I replace X and Y

public void showFragment(Fragment f){
    getChildFragmentManager().beginTransaction().replace(R.id.container, f).commit();
    currentChildFragment = f;
}

Can anyone point me in the right direction? Thanks a lot!

¿Fue útil?

Solución

If I got it right, you have Activity -> Fragment with container and in that container, you put/replace fragments between X and Y. Why do you have that fragment (F) level?

Anyway you are replacing fragments by id, so you can retrieve the current fragment with findFragmentById

Fragment fragment = getChildFragmentManager().findFragmentById(R.id.container);
if(fragment != null){
  if(fragment instanceof FragmentX) (..)
  else (..)
}

That code could be contained as a method of your F fragment (as we use getChildFragmentManager()). To send back that information to the activity itself, this one has to find the F fragment (it has to have an id) and call that method where you would check which fragment is showed (X or Y). It could be simplified if you remove the Fragment F level but I guess you reuse the same fragment somewhere else.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top