android - Action bar tabs - how to retrieve value from fragments in Activity? -
i've settings activity, has 3 tabs (each tab contains fragment) + in main activity there buttons row - buttons ok, , cancel.when press ok, this:
1) custom variables fragments 2) save them shared prefs
but how access fragment variables? tried this:
adding tabs in main activity:
actionbar.tab tab1 = actionbar.newtab().settext(res.getstring(r.string.actsettingstab1)); tab1.settablistener(new mytabslistener(new tab1fragment(), "tab1")); actionbar.addtab(tab1); //...similar tabs
this tab listener:
class mytabslistener implements actionbar.tablistener { private fragment fragment; private string tag; public mytabslistener(fragment fragment, string tag) { this.fragment = fragment; this.tag = tag; } @override public void ontabreselected(tab tab, fragmenttransaction ft) { // nil } @override public void ontabselected(tab tab, fragmenttransaction ft) { ft.replace(r.id.fragment_container, fragment, tag); } @override public void ontabunselected(tab tab, fragmenttransaction ft) { ft.remove(fragment); } }
and how variables fragments:
tab1fragment tab1 = (tab1fragment) fm.findfragmentbytag("tab1"); tab2fragment tab2 = (tab1fragment) fm.findfragmentbytag("tab2"); tab3fragment tab3 = (tab1fragment) fm.findfragmentbytag("tab3");
but it's unusual - findfragmentbytag returns fragment selected tab, otherwise returns null. when have selected tab1 , press ok, findfragmentbytag homecoming fragment tab1, null others.
maybe i'm doing wrong, or whole tring goind wrong way. how retrieve values fragments in parent activity , save them shared preferences?
separate process 2 steps:
1) gather settings fragments in real time (i.e. changed user). utilize listener pattern, fragments expose interface notify attached listener when user modifies of settings given fragment responsible for. allow activity attach listener fragments, , capture changes (store them in construction suits you).
2) allow activity save settings using sharedpreferences when ok button clicked. not have access fragments settings user has changed.
this way not have access fragments @ once, impossible if removed memory (as not visible anyway @ given time). instead, can re-assign activity listener selected fragment every time gets selected/displayed.
android android-fragments android-actionbar
No comments:
Post a Comment