android - How to restore fragment state after resume w/o savedInstanceState? -
in app fragmentactivity
contains simple listfragment
, want preserve position user has scrolled to. did following:
private int initialscrollposition = 0; private int initialscrollyoffset = 0; @override public void onsaveinstancestate (bundle outstate) { outstate.putint(scroll_position, this.getlistview().getfirstvisibleposition()); view firstvisibleitemview = this.getlistview().getchildat(0); outstate.putint(scroll_y_offset, (firstvisibleitemview == null) ? 0 : firstvisibleitemview.gettop()); } @override public void onactivitycreated (bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); this.restorestate(savedinstancestate); } private void restorestate(bundle savedinstancestate) { if(savedinstancestate != null && savedinstancestate.containskey(scroll_position)) { this.initialscrollposition = savedinstancestate.getint(scroll_position); } if(savedinstancestate != null && savedinstancestate.containskey(scroll_y_offset)) { this.initialscrollyoffset = savedinstancestate.getint(scroll_y_offset); } } @override public void onstart () { super.onstart(); // other gui stuff this.getlistview().setselectionfromtop(this.initialscrollposition, this.initialscrollyoffset); }
this solution works fine things display orientation changes or moving 1 activity
of app next.
but if fire app, scroll bit, go home, , restore app recents, onactivitycreated
(or other callbacks savedinstancestate
bundle
) not called , therefore state cannot restored.
therefore have 2 questions:
- what can
savedinstancestate
after resuming withoutonxxxcreated
callbacks? - what lifecycle doing there. i'd understand, why approach fails.
thank insight!
solution:
thx andré! changed onsaveinstancestate
this:
@override public void onsaveinstancestate (bundle outstate) { this.initialscrollposition = this.getlistview().getfirstvisibleposition(); view firstvisibleitemview = this.getlistview().getchildat(0); this.initialscrollyoffset = (firstvisibleitemview == null) ? 0 : firstvisibleitemview.gettop(); outstate.putint(scroll_position, this.initialscrollposition); outstate.putint(scroll_y_offset, this.initialscrollyoffset); }
if app brought front using recent apps button, might isn't recreated, because system didn't finish yet. in case onresume()
, following callbacks invoked.
conclusion: try restore position in onresume()
, store positions in onpause()
(for recent app switches activity isn't recreated), extract positions savedinstancestate
bundle (for orientation change activity recreated).
Comments
Post a Comment