android - Fragment on Screen Rotation -
i have added viewpager activity contains 2 page.
in oncreate of activity add fragments fragmentadapter:
public void oncreate(bundle savedinstancestate) { ...... fragmentadapter fragmentadapter = new fragmentadapter ( getsupportfragmentmanager(), new fragment[]{fragmentgame.builder(id), fragmentcomments.builder(id)}, new string[]{getstring(r.string.gameinfo), getstring(r.string.comments)} ); viewpager viewpager = (viewpager) findviewbyid(r.id.viewpager); viewpager.setadapter(fragmentadapter); public static fragmentgame builder(long id) { fragmentgame fragmentgame = new fragmentgame(); // fragmentgame.id = id; bundle bundle = new bundle(); bundle.putlong(constants.extra_id, id); fragmentgame.setarguments(bundle); return fragmentgame; }
first time activity created oncreateview of fragment called it's expected.
the strange behaviour when screen rotated first time oncreateview of fragment called twice second call has correct id , first call id 0.
on second screen rotation, oncreateview called 3 times , again last 1 has id.
by more screen rotation, oncreateview calls increase.
i found related question fragment , screen rotation can't figure out why happens , how right way.
----- update ------
the id problem solved replaced bundle direct value setting.
every time rotate device creating new fragment , adding fragmentmanager.
all of created fragments still in fragmentmanager therefore count increases 1 each time.
if wish retain value in fragment, need store in arguments otherwise values contains lost when system re-creates fragment.
public static fragmentgame builder(long id) { bundle args = new bundle(); args.putint("id", id); fragmentgame f = new fragmentgame(); f.setarguments(args); }
rather creating new fragment, suspect want retrieve created 1 when rotate device. use getsupportfragmentmanager().findfragmentbyid()
or getsupportfragmentmanager().findfragmentbytag()
this.
edit: code
// add fragment manager fragmenttransaction trans=getsupportfragmentmanager().begintransaction(); trans.add(f,"mytag"); trans.commit(); // retrieve fragment fragment f= getsupportfragmentmanager().findfragmentbytag("mytag");
just attempt retrieve fragment, if value null, create new fragment , add manager otherwise use retrieved one.
Comments
Post a Comment