Fragment Field is NULL after rotate device in Android

后端 未结 4 954
攒了一身酷
攒了一身酷 2021-01-23 11:39

When I start the app everything works ok but when I rotate to landscape it crashes because in the Fragment there is a field that is NULL.

I don

4条回答
  •  日久生厌
    2021-01-23 12:36

    Use setRetainInstance(true) is not a good approach. If you need to same some simple information such as: position of recyclerView, selected item of recyclerView, maybe some model(Parcelable) you could do it with method onSaveInstanceState / onRestoreInstanceState, there is one limitation is 1MB. Here is an example with animations how it works.

    For more durable persistance use SharedPreferences, Room(Google ORM) or you could try to use ViewModel with LiveData (best approach some data which should live while user session).

提交回复
热议问题