In the actual project development process fragment more and more, we certainly need to encounter fragment destroyed reconstruction situation. Combine your own project development to summarize and learn the code of open source projects, continue to share their own summary of fragment.
1.Fragment save what does the state save before it is destroyed?
We know that fragment instances will be destroyed by the system in many cases, and when our fragment back to the screen, we want to destroy the state before the destruction, so we need to save the state of fragment when the fragment is destroyed. Back to our question, what does fragment save before the state is saved? TextView text, or webview loading content? It seems that the problem is a bit complicated. Android system designers have designed a preservation mechanism for us, and we don't have to think about these issues at all. Let's take a look at TextView's source code:
@Override public parcelable onsaveinstancestate () {parcelable SuperStat E = super . Onsaveinstancestate (); } @Override public void onrestoreinstancestate (parcelable state) {if (!) ( State instanceof savedstate) {super . Onres Toreinstancestate (state); return ; } savedstate SS = (savedstate) state; super . Onrestoreinstancestate (Ss.getsuperstate ()); }
Look at the code above to believe from the literal meaning that you can also understand that the above code saves TextView State and restores the state when the control is restored. We go to check the source of the ListView, our base class Abslistview source will also see similar onsaveinstancestate, Onrestoreinstancestate method. For the ListView control, here's one thing we need to note that when the ListView destroys the recovery, we can't restore the ListView to the bound data state. Because the implementation of the ListView is based on the design implementation of the adapter pattern, the ListView does not care about the data that is responsible for presenting the data or the data source.
Now that we know the recovery of the fragment state, due to the design of the powerful mechanism of Google's siege Lion, we do not have to consider the recovery of the control's own state (the recovery of control data such as ListView will be said below). So what are we going to think about? The following can be summarized below:
- We have to consider the implementation of the third-party control, whether it is considered comprehensive when restoring the control state;
- Save the state of the member variable of the fragment (the position where the scrollview is currently sliding, the picture of the user action tag, and so on).
The first case is not the focus of our discussion, we mainly discuss the state preservation of the second case. In combination with our own project experience, we have two ways to save:
The first method of implementation:
Let's combine the data state recovery of the ListView to illustrate the standard implementation of state recovery for fragment.
Public class xxxfragment extends Fragment { Private Static FinalString view_position ="View_postion";PrivateListView ListView;@Override PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview = (viewgroup) inflater.inflate (r.layout.order_list_fragment, container,false); Initview (Rootview, Inflater);if(Savedinstancestate! =NULL) {//BiaoshiMcurrentpage = Savedinstancestate.getint (view_position);//re-request data (from cache), ListView bind data, reset last browse location Mcurrentpage}Else{//First request data, ListView binding Data}returnRootview; }/ * Save current frament status * / @Override Public void onsaveinstancestate(Bundle outstate) {Outstate.putint (view_position, mcurrentpage);Super. Onsaveinstancestate (Outstate); }}
The first method of implementation:
By studying the Photup project of the Chrisbanes, we recorded the fragment state with the Controller class object, and the controller was initialized in the oncreate of application. We can understand the state of fragment we use global variables in the record. Because the Photup project manages the state information of the fragment, we can not worry about fragment being destroyed when the state is saved, we re-instantiate a new fragment and restore the state before destroying it each time we call fragment. Concrete project implementation I will not give it here, see Chrisbanes's Photup project implementation.
For the implementation of Chrisbanes, I personally feel that some views:
1. I think the advantage of this approach (Fragment + Controller) is that it facilitates the communication of multiple Fragment under the same activity, and is flexible and convenient as a small project. If you develop a business complex project, this approach can result in too many global congtroller objects.
2. I feel that such fragment + controller way to implement the service can be borrowed, the general project service will not be too much, and (Service + Controller) way also aspects of service and other components of communication.
Management of fragment destruction and reconstruction
In learning Wordpress-androi source implementation, learning to WordPress through the Viewpager to achieve the fragment management of the activity of the greatest simplification of our management of fragment destruction and reconstruction. (Ps:wordpress-android source is worth learning far more than this point, if you are interested, to see the realization of wordpress-android, there will be a lot of harvest).
Some notes on the management of fragment, in my previous blog fragment some of the actual development of the summary of some of the fragment was destroyed by the system to rebuild the management of some problems, We through the previous imitation of QQ home page example through the wordpress-android way to achieve once. Let's rewrite Viewpager some methods:
Public class hviewpager extends viewpager { Private Booleanmpagingenabled =true; Public Hviewpager(Context context) {Super(context); } Public Hviewpager(context context, AttributeSet attrs) {Super(context, attrs); }@Override Public Boolean onintercepttouchevent(Motionevent ev) {if(mpagingenabled) {Try{return Super. onintercepttouchevent (EV); }Catch(IllegalArgumentException e) { } }return false; }@Override Public Boolean ontouchevent(Motionevent ev) {if(mpagingenabled) {Try{return Super. ontouchevent (EV); }Catch(IllegalArgumentException e) { } }return false; }/* Set whether to turn off Viewpager's sliding effect (we can switch between Viewpager fragment like activity switching) */ Public void setpagingenabled(Booleanpagingenabled) {mpagingenabled = pagingenabled; }}
Then we use Hviewpager corresponding Fragmentpageradapter subclass Switchpageradapter is responsible for the management fragment, the simple implementation is as follows:
Public class switchpageradapter extends fragmentpageradapter { Private Static Final intNum_tabs =2;Private Static Final intTab_message =0;Private Static Final intTab_call =1; Public Switchpageradapter(Fragmentmanager FM) {Super(FM); }@Override Public int GetCount() {returnNum_tabs; }@Override PublicFragmentGetItem(intPosition) {Switch(position) { CaseTab_message:return NewMessagefragment (); CaseTab_call:return NewCallfragment ();default:return NULL; } }}
Let's look at the switching effect of the home page now as follows:
Public class switchactivity extends fragmentactivity { PrivateButton Btn_message, Btn_call;PrivateHviewpager Viewpager; Public Static Final intMessage_fragment_type =1; Public Static Final intCall_fragment_type =2; Public intCurrentfragmenttype =-1;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); This. Requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.activity_switch); Btn_message = (Button) Findviewbyid (r.id.btn_message); Btn_call = (Button) Findviewbyid (R.id.btn_call); Viewpager = (Hviewpager) Findviewbyid (R.id.viewpager); Switchpageradapter adapter =NewSwitchpageradapter (Getsupportfragmentmanager ()); Viewpager.setpagingenabled (false); Viewpager.setadapter (adapter); Btn_message.setonclicklistener (Onclicker); Btn_call.setonclicklistener (Onclicker);if(Savedinstancestate! =NULL) {intindex = Savedinstancestate.getint ("Currentfragmenttype");if(Index >0) Switchpager (1);ElseSwitchpager (0); }Else{Switchpager (0); } }Private void Switchpager(intIndex) {viewpager.setcurrentitem (index); Currentfragmenttype = index; }/ * Save the currently displayed page */ @Override protected void onsaveinstancestate(Bundle outstate) {Super. Onsaveinstancestate (Outstate); Outstate.putint ("Lastfragmenttag", Currentfragmenttype); }PrivateOnclicklistener Onclicker =NewOnclicklistener () {@Override Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.btn_message:btn_message.settextcolor (Color.parsecolor ("#df3031")); Btn_call.settextcolor (Color.White); Btn_message. Setbackgroundresource (r.drawable.baike_btn_pink_left_f_96); Btn_call.setbackgroundresource (r.drawable.baike_btn_trans_right_f_96); Switchpager (0); Break; CaseR.id.btn_call:btn_message.settextcolor (Color.White); Btn_call.settextcolor (Color.parsecolor ("#df3031")); Btn_message. Setbackgroundresource (r.drawable.baike_btn_trans_left_f_96); Btn_call.setbackgroundresource (r.drawable.baike_btn_pink_right_f_96); Switchpager (1); Break; } } };}
The above is achieved through Viewpager to achieve management fragment destruction and reconstruction. In the Wordpress-android source code implementation of the fragment on the principle of management is almost like this, of course, the implementation of Wordpress-android in code writing can learn more than that. In addition to code writing, wordpress-android interface effect using fragment to achieve a lot of good use effect. The following Post Wordpress-android Blog editor editing interface only with a activity+ multiple fragment implementation effect, implementation or is quite to force.
PS: The first time with Markdown editor, really still a bit not accustomed to the format of learning.
Reprint Please specify source: http://blog.csdn.net/johnnyz1234/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Summary of the practical development of fragment (II.)