Summary of Fragment Development (2) and fragment Summary

Source: Internet
Author: User

Summary of Fragment Development (2) and fragment Summary

There are more and more Fragment situations in the development process of the actual project. You must have encountered the destruction and reconstruction of Fragment. I will continue to share my Fragment summary with my summary of the project development and the code of the open-source project.

1. What is the status saved before Fragment is saved and destroyed?

We know that Fragment instances will be destroyed and recycled by the system in many cases. When our Fragment is back to the screen, what we want is the status before the destruction. Therefore, when Fragment is destroyed, we need to save the Fragment status. Let's go back to our question: what is the status of Fragment saved before it is saved and destroyed? Is TextView text or WebView content loaded? It seems that the problem is a bit complicated. Android system designers have designed a storage mechanism for us, so we don't have to consider these issues at all. Let's take a look at the source code of TextView:

@Override    public Parcelable onSaveInstanceState() {        Parcelable superState = super.onSaveInstanceState();    }    @Override    public void onRestoreInstanceState(Parcelable state) {        if (!(state instanceof SavedState)) {            super.onRestoreInstanceState(state);            return;        }        SavedState ss = (SavedState) state;        super.onRestoreInstanceState(ss.getSuperState());    }

Looking at the above code, I believe that everyone can understand the literal meaning. The above code saves the TextView status and restores the status when the control is restored. Let's check the source code of ListView. The source code of our base class AbsListView will also see methods similar to onSaveInstanceState and onRestoreInstanceState. For the ListView control, we need to note that when the ListView is destroyed and restored, the status of the ListView to the bound data cannot be restored. Because the implementation of ListView is based on the design and implementation of the adapter mode, ListView only cares about the data and displays the data, but does not care about the data source.

Now we know that the Fragment status is restored. Due to the powerful mechanism design of Google's siege lions, we don't need to consider restoring the control's own status (the following will be said about restoring control data such as ListView ). So what do we need to consider? It can be summarized as follows:

  • We should consider the implementation of third-party controls and whether they are comprehensive when restoring the control status;
  • Save the state of the member variables of Fragment (the position where the ScrollView is currently sliding, the image marked by the user operation, etc ).

The first case is not the focus of this discussion. We will mainly discuss the State Preservation of the second case. Based on our project experience, we have two storage methods:

The first implementation method:

The following describes the standard implementation of Fragment state recovery based on the data state recovery of ListView.

Public class XXXFragment extends Fragment {private static final String VIEW_POSITION = "view_postion"; private ListView listView; @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View rootView = (ViewGroup) inflater. inflate (R. layout. order_list_fragment, container, false); initView (rootView, inflater); if (savedInstanceState! = Null) {// biaoshi mCurrentPage = savedInstanceState. getInt (VIEW_POSITION); // re-request data (from cache), bind data to listView, and reset mCurrentPage} else {// the data requested for the first time, listView bind data} return rootView;}/** Save the current Frament status */@ Override public void onSaveInstanceState (Bundle outState) {outState. putInt (VIEW_POSITION, mCurrentPage); super. onSaveInstanceState (outState );}}
The first implementation method:

By learning the photup project of chrisbanes, we use the Controller class object to record the Fragment status. The Controller completes initialization in onCreate of the Application, we can understand the Fragment status. We use global variables to record the status. Because the photup project manages the Fragment status information, we don't have to worry about saving the status when the Fragment is destroyed. Every time we call Fragment, we instantiate a new Fragment and restore the state before destruction. The specific project implementation is not provided here. See the photup project implementation of chrisbanes.

For the implementation of chrisbanes, I personally think that:

1. I think the advantage of this implementation method (Fragment + Controller) is that it facilitates the communication and implementation of multiple Fragment in the same Activity, and is flexible and convenient as a small project. If you develop a complex project, this method will cause too many global Congtroller objects.

2. in my opinion, the Fragment + Controller method can be used for Service implementation. Generally, there are not many services in the project, and the Service + Controller method also communicates with other components.

Management of Fragment destruction and Reconstruction

When learning the source code implementation of wordpress-androi, we learned that wordpress manages Fragment under the Activity through ViewPager, which greatly simplifies the management of Fragment destruction and reconstruction. (Ps: Wordpress-Android source code is worth learning more than that. If you are interested, you will surely get a lot from the implementation of wordpress-android ).

Some Notes on Fragment management are mentioned in the summary of Fragment's actual development in my previous blog: Some Questions about Fragment's destruction and reconstruction management by the system, we use wordpress-android to simulate the QQ homepage. We will first rewrite some ViewPager methods:

Public class HViewPager extends ViewPager {private boolean mPagingEnabled = 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 disable the sliding effect of ViewPager (we can implement switching between ViewPager Fragment, such as Activity switching) */public void setPagingEnabled (boolean pagingEnabled) {mPagingEnabled = pagingEnabled ;}}

Then we use the SwitchPagerAdapter subclass of FragmentPagerAdapter corresponding to HViewPager to manage Fragment. The simple implementation is as follows:

public class SwitchPagerAdapter extends FragmentPagerAdapter {    private static final int NUM_TABS = 2;    private static final int TAB_MESSAGE = 0;    private static final int TAB_CALL = 1;    public SwitchPagerAdapter(FragmentManager fm) {        super(fm);    }    @Override    public int getCount() {        return NUM_TABS;    }    @Override    public Fragment getItem(int position) {        switch (position) {        case TAB_MESSAGE:            return new MessageFragment();        case TAB_CALL:            return new CallFragment();        default:            return null;        }    }}

Let's take a look at the switching effect of the home page as follows:

Public class SwitchActivity extends FragmentActivity {private Button btn_message, btn_call; private HViewPager viewpager; public static final int vertex = 1; public static final int CALL_FRAGMENT_TYPE = 2; public int currentFragmentType =-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 = new SwitchPagerAdapter (getSupportFragmentManager (); viewpager. setPagingEnabled (false); viewpager. setAdapter (adapter); btn_message.setOnClickListener (onClicker); Btn_call.setOnClickListener (onClicker); if (savedInstanceState! = Null) {int index = savedInstanceState. getInt ("currentFragmentType"); if (index> 0) switchPager (1); else switchPager (0);} else {switchPager (0 );}} private void switchPager (int index) {viewpager. setCurrentItem (index); currentFragmentType = index;}/** Save the page currently displayed */@ Override protected void onSaveInstanceState (Bundle outState) {super. onSaveInstanceState (outState); outState. putInt ("lastFragmentTag", currentFragmentType);} private OnClickListener onClicker = new OnClickListener () {@ Override public void onClick (View v) {switch (v. getId () {case R. 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. export ke_btn_trans_right_f_96); switchPager (0); break; case R. 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 ;}}};}

ViewPager is used to manage Fragment destruction and reconstruction. In the WordPress-android source code implementation, the management principle of Fragment is similar. Of course, the implementation of WordPress-android can learn more from coding. In addition to coding, the WordPress-android interface uses Fragment to achieve a lot of good results. Below is a post on the WordPress-Android blog editor editing interface that uses only one Activity + multiple Fragment implementation results, which is quite powerful.



Ps: I used the markdown editor for the first time. I really don't want to get used to it. The format is learning.

Reprinted please indicate the source: http://blog.csdn.net/johnnyz1234/

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.