Explanation of Android fragments 7: fragement example

Source: Internet
Author: User

In the following example, we will experiment with all the content mentioned above. In this example, an activity contains two fragment items. One shows the playing tracks of Shakespeare's plays, and the other shows the abstract of the selected tracks. This example also demonstrates how to configure fragment with the screen size.

Create layout for the main activity.

@ Override <br/> protectedvoid oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); </P> <p> setcontentview (R. layout. fragment_layout); <br/>}
Layoutxml document of the main activity

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "horizontal" <br/> Android: layout_width = "match_parent" Android: layout_height = "match_parent"> </P> <p> <fragment class = "com. example. android. APIS. app. fragmentlayout $ titlesfragment "<br/> Android: Id =" @ + ID/titles "Android: layout_weight =" 1 "<br/> Android: layout_width =" 0px "Android: layout_height = "match_parent "/> </P> <p> <framelayout Android: Id =" @ + ID/details "Android: layout_weight =" 1 "<br/> Android: layout_width = "0px" Android: layout_height = "match_parent" <br/> Android: Background = "? Android: ATTR/detailselementbackground "/> </P> <p> </linearlayout>
The system initializes titlesfragment (used to display the Title List) when the activity loads this layout. The right side of titlesfragment is a framelayout, which is used to store the fragment for displaying the summary, but it is still empty, fragment is placed in framelayout only after a title is selected.

However, not all screens have enough width to hold the title list and abstract. Therefore, the preceding layout is only used for horizontal screen, and is now stored in RET/Layout-land/fragment_layout.xml.

In addition, when used for Portrait screen, the system uses the following layout, which is stored in RET/layout/fragment_layout.xml:

<Framelayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <br/> <fragment class = "com. example. android. APIS. app. fragmentlayout $ titlesfragment "<br/> Android: Id =" @ + ID/titles "<br/> Android: layout_width =" match_parent "Android: layout_height = "match_parent"/> <br/> </framelayout>

This layout only contains titlesfragment. This indicates that only the title list is displayed when a portrait screen is used. When you select an item, the program starts a new activity to display the abstract, instead of loading the second fragment.

Next, you will see the implementation of the fragment class. The first is titlesfragment, which is derived from listfragment. Most of the List functions are provided by listfragment.

When you select a title, the Code requires two actions: one is to display the created and abstract fragment in the same activity, and the other is to start a new activity.

Public static class titlesfragment extends listfragment {<br/> Boolean mdualpane; <br/> int mcurcheckposition = 0; </P> <p> @ override <br/> Public void onactivitycreated (bundle savedinstancestate) {<br/> super. onactivitycreated (savedinstancestate); </P> <p> // populate list with our static array of titles. <br/> setlistadapter (New arrayadapter <string> (getactivity (), <br/> android. r. layout. simple_list _ Item_activated_1, Shakespeare. titles); </P> <p> // check to see if we have a frame in which to embed the details <br/> // fragment directly in the containing UI. <br/> View detailsframe = getactivity (). findviewbyid (R. id. details); <br/> mdualpane = detailsframe! = NULL & detailsframe. getvisibility () = view. visible; </P> <p> If (savedinstancestate! = NULL) {<br/> // restore last State for checked position. <br/> mcurcheckposition = savedinstancestate. getint ("curchoice", 0); <br/>}</P> <p> If (mdualpane) {<br/> // in dual-pane mode, the List View highlights the selected item. <br/> getlistview (). setchoicemode (listview. choice_mode_single); <br/> // make sure our UI is in the correct state. <br/> showdetails (mcurcheckposition); <br/>}< br/>} </P> <p> @ override <br/> Public void onsaveinstancestate (bundle outstate) {<br/> super. onsaveinstancestate (outstate); <br/> outstate. putint ("curchoice", mcurcheckposition); <br/>}</P> <p> @ override <br/> Public void onlistitemclick (listview L, view V, int position, long ID) {<br/> showdetails (position ); <br/>}</P> <p>/** <br/> * helper function to show the details of a selected item, either by <B R/> * displaying a fragment in-place in the current UI, or starting a <br/> * whole new activity in which it is displayed. <br/> */<br/> void showdetails (INT index) {<br/> mcurcheckposition = index; </P> <p> If (mdualpane) {<br/> // We can display everything in-place with fragments, So update <br/> // the list to highlight the selected item and show the data. <br/> getlistview (). setitemchecked (I Ndex, true); </P> <p> // check what fragment is currently shown, replace if needed. <br/> detailsfragment details = (detailsfragment) <br/> getfragmentmanager (). findfragmentbyid (R. id. details); <br/> If (details = NULL | details. getshownindex ()! = Index) {<br/> // make new fragment to show this selection. <br/> details = detailsfragment. newinstance (INDEX); </P> <p> // execute a transaction, replacing any existing fragment <br/> // with this one inside the frame. <br/> fragmenttransaction Ft = getfragmentmanager (). begintransaction (); <br/> ft. replace (R. id. details, details); <br/> ft. settransition (fragmenttransaction. transit_fragment_fade); <br/> ft. commit (); <br/>}</P> <p>} else {<br/> // otherwise we need to launch a new activity to display <br/> // The dialog Fragment with selected text. <br/> intent = new intent (); <br/> intent. setclass (getactivity (), detailsactivity. class); <br/> intent. putextra ("Index", index); <br/> startactivity (intent); <br/>}< br/>}
The second fragment and detailsfragment show the abstract of the selected title:

Public static class detailsfragment extends fragment {<br/>/** <br/> * Create a new instance of detailsfragment, initialized to <br/> * show the text at 'index '. <br/> */<br/> Public static detailsfragment newinstance (INT index) {<br/> detailsfragment F = new detailsfragment (); </P> <p> // supply index input as an argument. <br/> bundle ARGs = new bundle (); <br/> args. putint ("Index", index); <br/> F. setarguments (ARGs); </P> <p> return F; <br/>}</P> <p> Public int getshownindex () {<br/> return getarguments (). getint ("Index", 0); <br/>}</P> <p> @ override <br/> Public View oncreateview (layoutinflater Inflater, viewgroup container, <br/> bundle savedinstancestate) {<br/> If (Container = NULL) {<br/> // we have different layouts, and in one of them this <br/> // fragment's containing frame doesn't exist. the fragment <br/> // may still be created from its saved state, but there is <br/> // no reason to try to create its view hierarchy because it <br/> // won't be displayed. note This is not needed -- We cocould <br/> // just run the code below, where we wocould create and return <br/> // The View hierarchy; it woshould just never be used. <br/> return NULL; <br/>}</P> <p> scrollview scroller = new scrollview (getactivity ()); <br/> textview text = new textview (getactivity (); <br/> int padding = (INT) typedvalue. applydimension (typedvalue. complex_unit_dip, <br/> 4, getactivity (). getresources (). getdisplaymetrics (); <br/> text. setpadding (padding, padding); <br/> scroller. addview (text); <br/> text. settext (Shakespeare. dialogue [getshownindex ()]); <br/> return scroller; <br/>}< br/>}
If the current layout does not have R. Id. detailsview (it is used in the detailsfragment container), the program starts detailsactivity to display the summary.

The following is the detailsactivity, which is simply embedded with detailsfragment to display the abstract.

Public static class detailsactivity extends activity {</P> <p> @ override <br/> protected void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); </P> <p> If (getresources (). getconfiguration (). orientation <br/> = configuration. orientation_landscape) {<br/> // If the screen is now in Landscape mode, we can show the <br/> // dialog in-line with the List so we don't need this activity. <br/> finish (); <br/> return; <br/>}</P> <p> If (savedinstancestate = NULL) {<br/> // during initial setup, plug in the details fragment. <br/> detailsfragment details = new detailsfragment (); <br/> details. setarguments (getintent (). getextras (); <br/> getfragmentmanager (). begintransaction (). add (Android. r. id. content, details ). commit (); <br/>}< br/>}
Note that this activity will end itself when detecting a portrait screen, so the main activity will take over it and display titlesfragment and detailsfragment. This can be displayed in titlefragment when the user is on the portrait screen, but the user rotates the screen and turns the display into a horizontal screen.

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.