Simple use of Fragment

1. Fragment is to avoid the use of Activity, because it consumes time when creating and destroying frequently. 2. Its characteristics: Fragment is light The use of activity, Fragment does not need to be registered in the manifest file (fragments are widely used on tablets and large screens) Fragment use: 1: Static use of Fragment Static use is to treat Fragment as a normal control and write it directly In the layout file of the Activity. Use steps: 1. Create a class and inherit Fragment 2. Rewrite the Fragment's onCreateView() lifecycle method and return a View 3. Use  NOTE: this fragment must have unique tags, such as tag or code that creates fragment id ** class: public class newFragment extends fragment {public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate (R .layout.fragment_new, container, false); }}**Code in the layout file: < /pre> 

Result display:

wKioL1e7ydSDnp1jAABGAjn7cmo451.png-wh_50

Second, use Fragment dynamically


First of all: you need to In the displayed page, the placeholder in the layout file

Then:

In Activity: 1. Get the manager object of the Fragment

2, open Fragment transaction processing

3, instantiate the fragment to be displayed and perform operations on the data

4, dynamically display the fragment

5. Submit the transaction

Code in the xml file:

Use layout placeholder

  


< p>Code in Activity:

FragmentManagerfragmentManager=getFragmentManager();FragmentTransactionfragmentTransaction=fragmentManager.beginTransaction();NewFragmentmyfrg=newNewFragment(); fragmentTransaction.replace(R.id.newfragment_id,myfrg );fragmentTransaction.commit();

Leave a Comment

Your email address will not be published.