Android Learning Path (22) Apply fragment build dynamic ui--build a flexible UI

Source: Internet
Author: User

When you design your app to support multiple screen sizes. You can optimize the user experience by reusing fragment on different layouts based on the available screen space.

For example, on a mobile phone. The user experience is more appropriate when using single-sided panels, which only show one fragment at a time. For example, on a handset device it might is appropriate to display just one fragment at a time for a single-pane user int Erface. Instead, you might want to set up side-by fragments on a tablet that can display a lot of other information.

Figure 1. Different fragment configurations that the same activity shows on different screen sizes. On a large screen. Two fragment are displayed side-by, while on a small screen device, only one fragment can be shown at a time. User action is required to toggle them.

FragmentManagerclass provides a way to add, remove, and replace fragment at execution time, creating a dynamic user experience on the line.

Add a fragment to the activity at execution time

Unlike defining fragments directly in the activity's layout file (using the,<fragment> element, as shown in the previous lesson). You can add a fragment when the activity executes. It is very necessary to assume that you intend to change fragment during the life cycle of the activity.

To run a join or remove fragment operation, you must use the FragmentManager create one FragmentTransaction , which provides add, remove, replace, and APIs to run other fragment transactions.

Suppose your activity consents to fragments being removed or replaced. Then you need to include the method of initializing these fragments in the OnCreate () method of the activity.

When using fragment, especially dynamically joined fragment, there is an important rule that fragment must have a container view to use as a container for fragment.

The previous lesson shows a layout that shows one fragment at a time, and the following layout is an option for that layout in the previous lesson.

In order to use the switch between fragment, the activity layout includes an empty FrameLayout container as a fragment.

Note that this file name is the same as the file name in the previous lesson, but his layout folder does not include the Lager qualifier, so this layout is for small screen devices, as this screen does not display two fragment at the same time.

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"/> 

In your activity. Using the Support library package API, call getSupportFragmentManager() to get one FragmentManager . Then call beginTransaction() to create one FragmentTransaction . Then call the add() method to add a fragment.

You can use FragmentTransaction to run multiple fragment transactions for activity.

Finally (when you are ready to change). You must call the commit() method.

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 (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 this fragment has been dynamically added to this container during execution- FrameLayout -rather than being defined in the <fragment> element of the activity's layout file. This activity can remove the fragment or replace the fragment.

Replace a fragment

The process of replacing fragment is very similar to the process of joining fragment, unlike the method, which requires calling the replace() method add() .

Keep in mind that when you run a fragment transaction, such as replacing or removing one, this generally will allow the user to return or undo these changes. To allow the user to return a fragment transaction, you must call the method before committing the fragment transaction addToBackStack() .

tip: When you remove or replace a fragment and add the transaction to the return stack, the removed fragment will be stopped (not destroyed). Assuming the user returns to this fragment again, it restarts (instead of creating again). Assuming that you did not add it to the return stack, the fragmen is destroyed directly when it is removed or replaced.

Examples of replacing fragment:

//Create fragment and give it an argument specifying the article it should Showarticlefragme NT Newfragment = new Articlefragment (); 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 (); 

addToBackStack()The method needs to pass in the argument of a string type to specify a unique name for this transaction. Suppose you intend not to use advanced fragment to manipulate APIs FragmentManager.BackStackEntry . The name is not a character.

Android Learning Path (22) Apply fragment build dynamic ui--build 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.