Android Transition between Fragments

Asked

Viewed 628 times

0

I have an application that contains 2 Ragments. An Fragment (A) is an item listing and Toolbar has a search, and the second (B) is the date of the selected item. I can make the transition well from A ->B and vice versa. My problem is in the search of framgent A (the search is sequential, as you write, the listing is filtered taking into account the field of the search). Then I click on the item to go to delhalhe (and Toolbar is without the search, as I want), but when I back I wanted to keep the search open with the text entered by the user.

Can someone help me?

  • Kiotto, recommend taking a look at OnBackStackChangedListener that you can add to FragmentManager. With it you can know that the user returned to the previous Fragment and restore the SearchView.

  • Without wanting to push too hard, you could make an example of sff code?

1 answer

1

In that case, I would recommend the interface OnBackStackChangedListener, that registered with the FragmentManager can handle any transaction event from Fragment's who manage records on BackStack. That is, with each transaction, you need to use the FragmentTransaction.addToBackStack, what you must already be doing.

The example for your use case would be:

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

    // Seu codigo de inicializacao, caso haja
    getFragmentManager().addOnBackStackChangedListener(this);
    // Ou
    // getSupportFragmentManager().addOnBackStackChangedListener(this);
}

@Override
public void onBackStackChanged() {
    // Verifica se o Fragment inicial esta visivel
    // Caso afirmativo, atualizar o SearchView
}

To recover the Fragment that is visible, you can use those flags (isVisible, isHidden) or even use the FragmentManager.findFragmentById or FragmentManager.findFragmentByTag and check if any instance returned.


There is another way by checking the BackStack, but I’m not sure if it’s the best approach compared to the previous one (kick that wouldn’t know which last entry was removed, but the last one that’s still in the stack). That way I’d have to retrieve the name of BackStackEntry (remembering to put the same name on addToBackStack) to check whether the second Fragment was removed.

An example would be:

Fragment fA = getFragmentManager().findFragmentByTag("FA");
Fragment fB = new Fragment();

getFragmentManager().beginTransaction().remove(R.id.container, fA).add(R.id.container, fB).addToBackStack("FA_FB").commit();

Then on onBackStackChanged:

FragmentManager fm = getFragmentManager();
FragmentManager.BackStackEntry entry = backfm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1);

if(entry.getName().equals("FA_FB")) {
    // TODO Atualizar SearchView...
}

Remembering that the above method I’m not sure, I need to check in my environment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.