java - class life cycle with ActionBar Sherlock Tab fragments -
i'm working on 1 of first android applications , got stuck understanding of how controllers/classes lifecycle arranged. i'm coming ios background.
basicly did following simple tutorial
so understand bind tablistener fragment. when switching tabs tablistener's ontabselected()
gets called , each time new instance of fragmenta/fragment b created.
that leads fact every time switch tabs oncreate..()
methods called again.
i don't want create new fragment instance every time switch tabs rather use 1 created intially @ application start.
the question how can switch tabs without killing fragments in there?
you can achieve attaching/detaching fragments, on tab listener every time tab unselected detach current fragment , on ontabselected method check if have created fragment before.
private fragment mfragment; private final string mtag; private final class<t> mclass; public tablistener(string ptag, class<t> pclass) { mtag = ptag; mclass = pclass; } @override public void ontabselected(tab tab, fragmenttransaction ft) { if ( mfragment == null ) { try { mfragment = (fragment)mclass.newinstance(); } catch (instantiationexception e) { e.printstacktrace(); } catch (illegalaccessexception e) { e.printstacktrace(); } ft.add(r.id.fragment_container,mfragment,mtag); } else { ft.attach(mfragment); } } @override public void ontabunselected(tab tab, fragmenttransaction ft) { if ( mfragment != null ) { ft.detach(mfragment); } } public void ontabreselected(tab tab, fragmenttransaction ft) { //nothing }
then can instantiate listener in
tablistener l = new tablistener<myfragment>(tabtag, myfragment.class)