Android Training-Get started-construct a flexible UI with Fragment construction dynamic ui-

Source: Internet
Author: User

Construct flexible UI Previous lesson Next lesson this lesson teaches you
    1. Add Fragment to Activity at run time
    2. Replace Fragment
You also need to read
    • Fragments
    • supports tablet and handheld devices
Try the Download sample

Fragmentbasics.zip

When you design your app to support a wide range of screen sizes, you can reuse your fragment in different layout configurations to optimize the user experience based on the available screen space.

For example, on a handheld device, it might be appropriate to display only one fragment at a time in a single-column user interface. Conversely, on a tablet, there is a wider screen size to show more information to the user, and you may set multiple fragment in parallel.

Figure 1. Two fragment, the same activity, are displayed in different configurations on different screen sizes. On a large screen, two fragment are arranged in parallel to fit the screen, but on a handheld device, only one fragment is appropriate at a time, and fragment must be replaced with each other when the user navigates.

FragmentManagerThe fragment class provides a way to add a runtime to the activity, remove fragment from the activity, and replace fragment in the activity, which you can use to create a dynamic user experience.

Add Fragment to Activity at run time

Instead of defining an activity in the layout file as the use element shown in the previous lesson <fragment> -you can add fragment to activity at run time. fragment- This is necessary if you want to change its fragment in the life cycle of the activity.

In order to perform a transaction, such as adding or removing a fragment, you must use the FragmentManager create one FragmentTransaction , which provides an API to add, delete, replace, and execute other fragment transactions.

If your activity allows fragment to be deleted or replaced, you should onCreate() add the initial fragment to activity in the activity's method.

An important rule for dealing with fragment-, especially the fragment-that you add when you run it, is that fragment must have a container in the layout that contains the fragment layout View .

The following layout is a substitute for displaying only one fragment layout at a time in the previous lesson. In order to replace the other with one fragment, the activity's layout contains an empty one as a fragment container FrameLayout .

Note that the file name is the same as the layout file in the previous lesson, but the layout directory does not have large qualifiers, so this layout is used for devices that are smaller than large , because the small screen is not suitable for displaying two fragment at a time.

res/layout/news_articles.xml:

<framelayout  xmlns:android " Span style= "COLOR: #660" >=   "http://schemas.android.com/apk/res/android"  Span style= "COLOR: #828" >android:id  =   @+id/ Fragment_container " android:layout_width  =   "match_parent"  android:layout_height  Span style= "COLOR: #660" >=   "match_parent"  /> 

In your activity, using the Support library API, the call getSupportFragmentManager() gets one FragmentManager . Then call beginTransaction() Create one FragmentTransaction and call add() add a fragment.

You can use the same one FragmentTransaction to perform multiple fragment transactions on the activity. When you are ready to make a change, you must call commit() .

For example, here's how to add a fragment to the previous layout:

Import Android.OS.Bundle;Import Android. Support.V4.app.fragmentactivity; Public class mainactivity extends fragmentactivity {    @Override     Public void onCreate(Bundle savedinstancestate) {        Super.onCreate(savedinstancestate);        Setcontentview(R.Layout.News_articles);        //Check whether the current activity uses Fragment_container framelayout        if (Findviewbyid(R.ID.Fragment_container) != NULL) {            //If you are recovering from a previous state, do not need to do anything that should be returned directly,            //will result in overlapping fragment            if (savedinstancestate != NULL) {                return;            }            //Create a new Fragment to be placed in the activity layout            headlinesfragment firstfragment = New headlinesfragment();                        //In case the activity is initiated by a Intent special instruction,            //Pass additional data of Intent as parameters to fragment            firstfragment.setarguments(getintent().Getextras());                        //Add fragment to ' Fragment_container ' framelayout            Getsupportfragmentmanager().BeginTransaction()                    .Add(R.ID.Fragment_container, firstfragment).Commit();        }    }}

Because fragment has been added to the container at run time FrameLayout -instead of defining-activity with elements in the activity's layout- <fragment> you can either delete this fragment or replace it with another fragment.

Replace Fragment

The process of replacing a fragment is similar to adding, but instead of using a replace() method add() .

Remember that when you perform fragment transactions, such as replacing or deleting a fragment, it is often appropriate to allow the user to navigate backwards and "undo" changes. In order to allow the user to navigate backwards in the fragment transaction, you must FragmentTransaction call before committing addToBackStack() .

Note: When you delete or replace a fragment and add a transaction to the return stack (back stack), the deleted fragment is stopped (not destroyed). If the user navigates back to recover this fragment, it restarts. If you do not add a transaction to the return stack, the fragment is destroyed when it is deleted or replaced.

Replace another example with one fragment:

//Create a fragment and give it a parameter to specify the text that needs to be displayedarticlefragment newfragment = New articlefragment();Bundle args = New Bundle();args.Putint(articlefragment.arg_position, position);newfragment.setarguments(args);fragmenttransaction Transaction = Getsupportfragmentmanager().BeginTransaction();//Use this fragment to replace something in the Fragment_container view//and add the transaction to the return stack so that the user can navigate backTransaction.Replace(R.ID.Fragment_container, newfragment);Transaction.Addtobackstack(NULL);//Commit a transactionTransaction.Commit();

addToBackStack()method receives an optional string parameter that specifies a unique name for the transaction. This name is not required unless you plan to use the FragmentManager.BackStackEntry API to perform some advanced fragment operations.

Last lesson Next lesson

Android Training-Get started-construct a flexible UI with Fragment construction dynamic ui-

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.