简体   繁体   中英

How to restore Android fragment view state

I have application titles fragment and contents fragment on the screen. When the user clicks on the item in titles fragment the according fragment is created and inserted to a frame and the selected title is highlighted in titles fragment.

Transaction is done with fragment.addToBackStack() , so when the user clicks the BACK key, the previous fragment is restored and inserted in the frame.

What is the best solution to restore view state when transaction manager restores fragments?

The problem is that I should highlight previous fragment name in titles fragment and I should know what fragment it is. I resolved it by storing view state in my own stack: when fragment is created and restoring on changing transaction backstack using transaction manager listener.

But this doesn't seem like the correct solution.

Before the answer, next time remember to add your code. Chances are my answer will not help you as much as it could because I don't really know your code.

This is old but anyway, IF I understand your question (and app architecture) correctly, it sounds like a case for interfacing.

Example:

add this interface as a member to the content fragment:

public class ContentFragment extends Fragment{

   public interface onFragmentTitleHighlighted{
      public void highLightTitle(String title);
   }
}

and have the title fragment implement it. Make sure to equip your content fragments with the title fragmnet, and add a call to highLightTitle(String title); in the content fragment's onCreateView(...) call. This way whenever a new content fragmnet is being added the title will be highlighted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM