android - Fragment with AsyncTask and Navigation Drawer - Best practice -


i write question because know best way manage context: have mainactivity navigation drawer , whenever select item in navigation drawer, create new fragment , through fragmenttransaction replace previous fragment new one.

now, in every fragment have asynctask performs task (eg download data web or perform query on local sqlite database).

my question is: how can avoid recreate every time fragment , restart asynctask when press element in navigation drawer? best way manage situation?

this method use in mainactivity display fragment when press item in navigation drawer:

private void displayview(int index) {      fragment f = null;      switch(index) {         case 1:             f = fragment1.newinstance();             break;         case 2:             f = fragment2.newinstance();             break;     }      if(f !=  null) {         fragmenttransaction ft = getsupportfragmentmanager().begintransaction();         ft.replace(r.id.container, f);          ft.commit();     } } 

thanks in advance!

hiding fragment alternative removing it. removal (if not added backstack) causes fragment torn down (pause, stop, destroyview, destroy, detach). hiding doesn't change fragment's lifecycle state, makes not visible. fragmenttransaction methods hide() , show(). initially, add both fragments, , hide unselected one. when fragment selected navigation drawer, if not visible, hide old selection , make new selection visible. this:

getsupportfragmentmanager()         .begintransaction()         .hide(oldselectedfrag)         .show(newselectedfrag)         .commit(); 

the visible/hidden status of fragment available using ishidden(). there fragment callback: onhiddenchanged(). keep in mind when fragment hidden still active in sense of being in started or resumed state. may want use hidden status disable refreshes or other actions needed when visible. if fragment has option menu, may want disable using setmenuvisibility() when fragment hidden. don't think fragmentmanager automatically.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -