java - How to attach() and detach() instead of add() and remove() to save fragment view -
i have following code actionbar
:
private class mytablistener implements actionbar.tablistener { private fragment mfragment; private final activity mactivity; private final string mfrag; public mytablistener( activity activity, string fragname ) { mactivity = activity; mfrag = fragname; } @override public void ontabreselected( tab tab, fragmenttransaction ft ) { // todo auto-generated method stub } @override public void ontabselected( tab tab, fragmenttransaction ft ) { mfragment = fragment.instantiate( mactivity, mfrag ); ft.add( android.r.id.content, mfragment ); } @override public void ontabunselected( tab tab, fragmenttransaction ft ) { ft.remove( mfragment ); mfragment = null; } }
i have textboxes within tab
fragments , switching between tabs forces app lose data added textbox. instead of add
, remove
, use attach
, detach
saves fragment state.
how accomplish within code have?
update:
the code looks this:
private class mytablistener implements actionbar.tablistener { private fragment mfragment; private final activity mactivity; private final string mfrag; public mytablistener( activity activity, string fragname ) { mactivity = activity; mfrag = fragname; } @override public void ontabreselected( tab tab, fragmenttransaction ft ) { // todo auto-generated method stub } @override public void ontabselected( tab tab, fragmenttransaction ft ) { //mfragment = fragment.instantiate( mactivity, mfrag ); //ft.add( android.r.id.content, mfragment ); mfragment = mactivity.getsupportfragmentmanager().findfragmentbytag(mfrag); if( mfragment == null ) { mfragment = fragment.instantiate(mactivity, mclass.getname()); ft.add(android.r.id.content, mfragment, mfrag); } else { ft.attach(mfragment); } } @override public void ontabunselected( tab tab, fragmenttransaction ft ) { //ft.remove( mfragment ); //mfragment = null; if (mfragment != null) { ft.detach(mfragment); } } }
and getting error following line:
mfragment = mactivity.getsupportfragmentmanager().findfragmentbytag(mfrag);
error:
the method getsupportfragmentmanager() undefined type activity
instead of rewriting code, use sharedpreferences
temporarily store variables being displayed.
in ondestroy
method of tab you're leaving, add variables preferences, , retrieve them when re-enter tab.
@override public void ondestroy(){ super.ondestroy(); log.i("ondestroy", "logged"); sharedpreferences prefs = getactivity().getsharedpreferences("name", context.mode_private); editor editor = prefs.edit(); editor.putstring("stringname", stringtostore); editor.commit(); }
Comments
Post a Comment