Android Fragment resolve

Android is open when required by FragmentManager to manage Fragment, each of Fragment add and remove services, such appropriate action by the transaction, and then commit the transaction.

In front of Fragment management, you need to open a transaction as follows:

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();

Fragment of the main methods of management under FragmentTransaction have add (), remove (), replace (), hide (), show (), detach (), attach ().

Add a Fragment way:
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx. add(R.id.content, new Fragment1(),"Fragment1");
        tx. commit();
Here is the bind Fragment1 directly add to the id of the content of View.

Add Fragment way:
         FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx. replace(R.id.content, new Fragment1(),"Fragment1");
        tx. commit();
As used herein, to add replace Fragment, replace the role equivalent to remove () + add () action of the combination . That will first use replace the current id is removed out Fragment on content, this is removed out of Fragment will be destroyed off (if the current transaction), then put the new Fragment to add to the View by add.

(1) Use replace mode, which is equivalent to the corresponding id FrameLayout content of only one layer, it is above Fragment1, by replace this way, will Fragment life cycle go again , if we get there Fragment operational data, then, will frequently go to pull data; use replace, Fragment binding of view will be destroyed, Fragment instances will not necessarily be destroyed , mainly to see if there is not added to the fallback stack.

(2) add the way through, we can add more layers on the content of FrameLayout id, i.e. you can be added to the plurality of Fragment FrameLayout by multiple add. This time, we can cooperate hide (), show () method to constantly switch between different Fragment. After we add the Fragment to add by way FrameLayout of View, to switch Fragment Another advantage through hide (), show () is, when a Fragment re-show show came out, it still retains the original data in the on Fragment, that is not hide and destroy Fragment, just simply hide it .

Published 39 original articles · won praise 19 · views 60000 +

Guess you like

Origin blog.csdn.net/u010090644/article/details/51482672