我最近開發了一種新的模式,通過保留的片段來存儲片段狀態。用這種方式保留狀態是否有缺點?
public class MyActivityOrFragment {
public void onSaveInstanceState(Bundle bundle) {
bundle.putInt("example", 123);
}
// plus restore in onCreate
}
我保持狀態的片段是這樣的::
public class MyActivityOrFragment {
public static class State extends Fragment {
int example = 123;
public void onCreate(...) {
...
setRetainInstance(true);
}
}
State state;
public void onCreate(Bundle ssi) {
if (ssi == null) {
state = new State();
getFragmentManager().beginTransaction().add(state, "state").commit();
} else {
state = (State) getFragmentManager().findByTag("state");
}
}
}
與很多國家保持這種減少這麼多的樣板,因爲我只是不停地在相反的onSaveInstanceState
保存的東西這樣的狀態片段,並知道它會自動保留。但是,使用保留的片段而不是像通常推薦的那樣保存到包中有什麼缺點?這太好了,難道是真的嗎?
看看這個:https://github.com/frankiesardo/icepick – Teodor