注册 | 登录

解决android - How to save state with navigation drawer and fragments

itPublisher 分享于



推荐:关于android抽屉,navigation drawer



I have an application with a navigation drawer, one activity and many fragments. When I change the device orientation my main activity is recreate and it's my main fragment who appears, not the current fragment. Just like when I launch the app.

How can I restore the current fragment and maybe the data associated with the selected fragment ?

I Have seen this post but it doesn't work : Save fragment state with navigation drawer

Thanks in advance to those who can help me.

android android-fragments navigation-drawer android-savedstate
  this question
asked Mar 13 '16 at 20:40 Tsuuki 30 4      did you tried adding configchanges to the manifest –  Sarthak Mittal Mar 13 '16 at 21:14      I thought of something that can be considered a hack; whenever you enter a new fragment, save its' position into the SharedPreferences and then onConfigurationChange read the position from SharedPrefs and instantiate the right fragment. –  Vucko Mar 13 '16 at 22:35


1 Answers


I've found that the fragment states are already persisted for you.

推荐:Android Navigation Drawer(导航抽屉)

  Google I/O 2013 Android 更新了Support库,新版本的Support库中新加入了几个比较重要的功能。 添加 DrawerLayout 控件,支持创建  Navigation Drawer模式。可

This is what I do: I check if savedInstanceState is null. If it is, I execute the FragmentManager transaction to display the main fragment. If it is not null, it means the fragment state is persisted. I don't do any kind of transaction, and the fragment is recreated for me from the persisted state.

  this answer
answered Mar 14 '16 at 1:47 kris larson 15.7k 2 18 26      Thanks for your help, in my onCreate I executed the FragmentManager to display one or another Fragment according to SharedPreferences. So I just added the condition on savedInstanceState == null. –  Tsuuki Mar 14 '16 at 19:58


推荐:Android – Toolbar 上的 Navigation Drawer

摘要 在 Material Design 发布后,Google 也开始陆续更新了 Google app 的界面,让大家有个范例可以看。而过去大力推动的 actionbar 自然而然也成了众开发者观注








您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱