Android official Getting Started document [17] building a flexible UI

Source: Internet
Author: User

Android official Getting Started document [17] building a flexible UI
Building a flexible UI
Build a flexible UI

This lesson teaches
1.Add a Fragment to the Activity at Runtime
2.Replace one Fragment with another

You should also read
? Fragments
? Supporting Tablets and handsets
This lesson teaches you
1. Add a fragment to an activity at run time
2. Replace a fragment with another fragment

You should also read
? fragment
? support for tablets and handheld devices

Try it Out
Give it a try.

Download the sample
Fragmentbasics.zip
Download sample
Fragmentbasics.zip

when designing your application to support a wide range of screens sizes, you can reuse yo ur fragments in different layout configurations-optimize the user experience based on the available-screen space.
When designing your application to support multiple screen sizes, you can reuse the user experience of the screen space available on the basis of different layout structure optimizations.

for example, on a handset device it might bes appropriate to display just one fragment at A time for a Single-pane user interface. Conversely, want to set fragments side-by-side on a tablet which have a wider screen size to display more Informati On to the user.
For example, a handheld device may also be the appropriate time for a single pane of the user interface to display only one fragment. Conversely, you may want to set the clip side-by-side with a wider screen size to show more information to the user.
 
Figure 1. Fragments, displayed in different configurations for the same activity on different screen sizes. On a large screens, both fragments fit side by side, but on a handset device, only one fragment fits at a time so the FRAGM Ents must replace each of the other as the user navigates.
Figure 1 of two clips for the same activity on different screen sizes are displayed in different configurations. On a large screen, the two fragments are intended to merge rows, but on a handheld device, only one fragment is assembled at a time so that the user navigation fragments must be replaced by each other.

The Fragmentmanager class provides methods, allow you to add, remove, and replace fragments to an activity at runtime In order to create a dynamic experience.
The Fragmentmanager class provides a number of methods that enable you to add, delete, and replace fragment activities at run time to create a dynamic experience.

Add a Fragment to the Activity at Runtime
Add a fragment to an activity at run time


--------------------------------------------------------------------------------

Rather than defining the fragments for a activity in the layout file-as shown in the previous lesson with the <fragmen T> element-you can add a fragment to the activity during the activity runtime. This was necessary if you plan to change fragments during the life of the activity.
Instead of qualifying the fragment as active in the layout file, the previous lesson with the < fragment > display element can be added to the clip's activity during the active run. This is necessary if you plan to change fragments within the life cycle of the activity.

To perform a transaction such as add or remove a fragment, you must use the Fragmentmanager to create a fragmenttransactio N, which provides APIs to add, remove, replace, and perform other fragment transactions.
In order to trade, such as adding or deleting fragments, you must use Fragmentmanager to create Fragmenttransaction, which provides the API to add, delete, replace, and perform other fragment transactions.

If your activity allows the fragments to being removed and replaced, you should add the initial fragment (s) to the activity D Uring the activity ' s OnCreate () method.
If your activity can make the fragment deleted, instead, you should add the initial fragment activity to the active OnCreate () method.

An important rule when dealing with fragments-especially when adding fragments in Runtime-is that your activity layout mus T include a container View in which you can insert the fragment.
An important rule when the fragment, especially in the overtime fragment with the processing run, is that your active layout must have a container view in which to insert the fragment.

The following layout is a alternative to the layout shown in the previous lesson that shows only one fragment at a time. In order to replace one fragment with another, the activity's layout includes an empty framelayout that acts as the Fragme NT container.
The following layout is an alternative to the layout shown in the previous lesson to show only one fragment at a time. In order to replace one fragment with another, the active layout consists of an empty framelayout acting as a fragment container.

Notice that the filename was the same as the layout file in the previous lesson, and the layout directory does not has the Large qualifier, so this layout was used when the device was smaller than large because the screen does not fit both Fragments at the same time.
Note that the file name is the same as in the previous lesson layout file, but the layout directory does not have a large qualifier, so this layout uses a device that has a smaller screen than large because the screen does not fit at the same time for two clips.

Res/layout/news_articles.xml:
<framelayout xmlns:android= "http://schemas.android.com/apk/res/android"
Android:id= "@+id/fragment_container"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"/>

Inside your activity, call Getsupportfragmentmanager () to get a fragmentmanager using the support Library APIs. Then call BeginTransaction () to the Create a fragmenttransaction and call Add () to add a fragment.
In your activity, call Getsupportfragmentmanager () to get the Fragmentmanager using the Support library API. Then call the BeginTransaction () to create a fragmenttransaction and call Add () to append a fragment.

You can perform multiple fragment transaction for the activity using the same fragmenttransaction. When you're ready for the changes, you must call commit ().
Multiple fragment transactions can be performed using the same fragmenttransaction 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:
For example, here is how the fragment is added 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 (savedinstancest        ATE);        Setcontentview (R.layout.news_articles); Check the activity is using the layout version with//the Fragment_container framelayout if (findvi            Ewbyid (r.id.fragment_container)! = null) {//However, if we ' re being restored from a previous state,             Then we don ' t need to do anything and should return or else//we could end up with overlapping fragments.            if (savedinstancestate! = null) {return;  }//Create a new Fragment to being placed in the activity layout headlinesfragment firstfragment = new                        Headlinesfragment (); In the This activity is started with special instructions from AN//Intent, pass THe Intent ' s extras to the fragment as Arguments firstfragment.setarguments (Getintent (). Getextras ()); Add the fragment to the ' Fragment_container ' Framelayout getsupportfragmentmanager (). Begintran        Saction (). Add (R.id.fragment_container, firstfragment). commit (); }    }}


Because The fragment have been added to the Framelayout container at Runtime-instead of defining it in the activity ' s layou T with a <fragment> element-the activity can remove the fragment and replace it with a different one.
Since the fragment has been added <fragment> the active definition of the element it can delete the fragment in the active layout and replace it with a different replace to the Framelayout container at run time.

Replace one Fragment with another
Replace a fragment with another fragment


--------------------------------------------------------------------------------

The procedure to replace a fragment are similar to adding one, but requires the replace () method instead of add ().
The step replacement fragment is similar to adding one, but requires the replace () method instead of add ().

Keep in mind if you perform fragment transactions, such as replace or remove one, it's often appropriate to allow t He user to navigate backward and "undo" the Change. To allow the user to navigate backward through the fragment transactions, you must call Addtobackstack () before you commit The fragmenttransaction.
Keep in mind that when you perform a fragment trade, such as replacing or deleting one, it is often appropriate to allow the user to browse backwards, "undo" the transition. In order for the user to be able to navigate backwards through the fragmented trade, you must call Addtobackstack () before you commit fragmenttransaction.

Note:when you remove or replace a fragment and add the transaction to the back stack, the fragment that's removed is STO Pped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you don't add the transaction to the back stack, then the fragment was destroyed when removed or replaced.
Note: When you delete or replace fragments and trades are added to the back of the stack, the stop fragment is removed (not broken). If the user navigates back to the recovery fragment, it restarts. If no transaction is added to the back stack and then removed or replaced, the fragment is destroyed.

Example of replacing one fragment with another:
An example of replacing a fragment with another:

Create fragment and give it an argument specifying the article it should showarticlefragment newfragment = new Articlef Ragment (); Bundle args = new bundle (); Args.putint (Articlefragment.arg_position, POSITION); newfragment.setarguments (args); Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction ();//Replace whatever is in the fragment _container view with this fragment,//and add the transaction to the back stack so the user can navigate BACKTRANSACTION.R Eplace (R.id.fragment_container, newfragment); Transaction.addtobackstack (null);//Commit the Transactiontransaction.commit ();


The Addtobackstack () method takes a optional string parameter that specifies a unique name for the transaction. The name isn ' t needed unless you plan to perform advanced fragment operations using the Fragmentmanager.backstackentry API S.
The Addtobackstack () method accepts an optional string parameter, specifying a unique name for the transaction. Unless you intend to execute the name of an advanced fragment operation using the Fragmentmanager.backstackentry API is not required.

Next:communicating with other fragments
Next: Communication and other fragments

This article is translated from: https://developer.android.com/training/basics/fragments/fragment-ui.html

Android official Getting Started document [17] building a flexible UI

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.