Common usage Summary of fragment in Android application UI development _android

Source: Internet
Author: User
Tags commit gettext

1.Fragment Overview
in an activity, fragment represents a part of the UI or an action. An activity can combine multiple fragment objects or different objects corresponding to the same fragment byte code in multiple activity. A fragment object must be embedded in a main activity object, and the lifecycle of the fragment is closely related to the main activity. For example, when the main activity is in the paused state, all the corresponding fragment objects are in the paused state, and only when the main activity is in the resumed state can the fragment be in a state of free control.


2. Create fragment
in order to create a fragment, you should inherit fragment or its subclasses and overwrite the corresponding method. such as OnCreate (), Oncreateview (), OnPause (), etc.
(1). Add UI Interface
To show a layout for the fragment, you must implement the Oncreateview () fallback method.
Note: When the fragment Inherits Listfragment, the Oncreateview () method does not need to be overridden because it returns a ListView object by default

public view Oncreateview (Layoutinflater inflater, ViewGroup container, 
  Bundle savedinstancestate) { 
 View view = Inflater.inflate (r.layout.list, null); 
 return view; 
} 

(2). Add Fragment to Activity
1. Through layout layout file
The Android:name property should be the full path of the fragment corresponding class.

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
 android:layout_width=" match_parent " 
 android:layout_height=" match_parent " 
 android:o" rientation= "Horizontal" > 
 
 <fragment 
  android:id= "@+id/list" 
  Com.example.news.ArticleListFragment " 
  android:layout_width=" 0DP " 
  android:layout_height=" Match_parent " 
  android:layout_weight= "1"/> 
 <fragment 
  android:id= "@+id/viewer" 
  Com.example.news.ArticleReaderFragment " 
  android:layout_width=" 0DP " 
  android:layout_height=" Match_ Parent " 
  android:layout_weight=" 2 "/> 
 
</LinearLayout> 

2). Through Java code
When the activity runs, it is free to add fragment objects to the activity, but you should specify a ViewGroup container that you can fragmenttransaction to complete fragment removal or substitution.

Manager = Getfragmentmanager (); 
if (Manager.findfragmentbytag ("right") = = null) { 
 manager.begintransaction (). Replace (R.id.right, new Rightfrag () , "right"). commit (); 
 

(3). Fragment Unique designator
Each fragment needs to define a unique identifier, and if the activity is destroyed and restarted, the system can restore the fragment state. If you want to recover, you need to meet one of the following 3 ways:
1). Define ID
In the layout file, define the Android:id property

<fragment 
 android:id= "@+id/list" 
 android:name= "Com.example.news.ArticleListFragment" 
 android: Layout_width= "0DP" 
 android:layout_height= "match_parent" 
 android:layout_weight= "1"/> 

2). Specify the tag
Specify tag when Android:tag indicates or a fragment object Add () or replace ()

<fragment 
 android:id= "@+id/list" 
 android:tag= "the" " 
 android:name=" Com.example.news.ArticleListFragment " 
 android:layout_width=" 0DP " 
 android:layout_height=" Match_parent " 
 android:layout_weight= "1"/> 

Or

Manager.begintransaction () 
 . Replace (R.id.right, New Rightfrag (), right)//indicates the fragment's tag 
. commit () in the transaction. ; 

3). ViewGroup ID
If the fragment has no ID and tag, the system will use the ID of the container view layout


3.Fragment of Management
through the Getfragmentmanager () method, we can get the Fragmentmanager object, mainly complete the following functions

Fragmentmanager manager = Getfragmentmanager ();
(1). Get the existing Fragment object
If the fragment specifies an ID in the layout file, the object is obtained by Findfragmentbyid (), or the tag can be specified by Findfragmentbytag ().

Fragment Fragment = Getfragmentmanager (). Findfragmentbytag ("right"); 
or 
Fragment Fragment = Getfragmentmanager (). Findfragmentbyid (ID); 

(2). Register Onbackstackchangedlistener Listener
can be used to monitor the return stack information for the task, and to perform the corresponding onbackstackchanged () method when the return stack state has changed

Manager.addonbackstackchangedlistener (New Fragmentmanager.onbackstackchangedlistener () { 
 @Override 
 public void onbackstackchanged () { 
  toast.maketext (mainactivity.this, "return heap state Changed", 1). Show (); 
 

(3). Pop-up return stack
The analog user clicks the Return key, pops the specified fragment from the return stack, and the operation is asynchronous. The prerequisite is that the fragment object uses the. BeginTransaction (). Addtobackstack ("right") to add the feed back stack

Manager.popbackstack (); Pop the top state off the back stack
(4). Fragmenttransaction Affairs
Transactions consist primarily of a set of operations, such as increasing the removal of replacements, animation settings, and so on

 
 * * * Open a transaction through the manager that contains a set of operations, which can be add (), remove (), replace () 
 * To complete the operation of the fragment, and use commit () Submit * * 
fragmenttransaction transaction = Manager.begintransaction (); 
 
Transaction.replace (R.id.right, New Rightfrag (), "right"); 
Transaction.settransition (Fragmenttransaction.transit_fragment_open);//Set Animation 
transaction.addtobackstack (" Right "); Add the fragment back to heap 
//COMMIT TRANSACTION 
transaction.commit (); 

(5). Fragment State Management

* 
 * Manage fragment Status 
 * If you add a fragment to a main activityviewgroup, 
 * If the phone screen spins, the current activity is destroyed and rebuilt, Fragment also be Activitymanager created 
 * So in onCreate, we need to judge the * * 
@Override 
protected void OnCreate (Bundle Savedinstancestate) { 
 super.oncreate (savedinstancestate); 
 Setcontentview (r.layout.activity_main); 
 Manager = Getfragmentmanager (); 
 if (Manager.findfragmentbytag ("right") = = null) { 
  //if (savedinstancestate = null) can also determine whether the fragment has been loaded 
 
  Manager.begintransaction () 
   . Replace (R.id.right, New Rightfrag (), right) 
   . Settransition ( Fragmenttransaction.transit_fragment_open)//Set animation 
   . Addtobackstack ("right")//Add the FRAGMENT back to heap 
  //COMMIT TRANSACTION 
  . commit (); 
 } 
} 


information interaction between 4.Fragment
(1). Obtain the object

 
 * * Click on the Fragment button to set the button's text to another fragment edittext literal value 
 * 
/public View Oncreateview ( Layoutinflater inflater, ViewGroup container, 
  Bundle savedinstancestate) { 
 View view = Inflater.inflate ( R.layout.list, null); 
 Final button button = (button) View.findviewbyid (r.id.confirm); 
 Button.setonclicklistener (New View.onclicklistener () { 
   
  @Override public 
  void OnClick (View v) { 
   // Find the EditText object in another fragment by Fragmentmanager, and get the text content 
   EditText edittext = (edittext) Getfragmentmanager (). Findfragmentbytag ("left"). GetView (). Findviewbyid (R.id.name)); 
   Button.settext (Edittext.gettext (). toString ()); 
  } 
 ); 
 return view; 
} 

(2). Pass Back off function

public class Mainactivity extends activity {private Fragmentmanager manager; 
 
 Private button button; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
   
  Setcontentview (R.layout.activity_main); Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {rightfragment 
    Rightfrag = (rightfragment) (Getfragmentmanager (). Findfragmentbytag ("right")); * * * Through the Set method, passing an instantiated object to it, due to the Rightfrag.set () method inside the implementation of the RightFragment.CallBack.get () method, complete the transfer of parameters/Rightfrag.set ( 
     New Rightfragment.callback () {@Override public void get (String str) {button.settext (str); 
   } 
    }); 
 } 
  }); 
 
 } public class Rightfragment extends Listfragment {private Loadermanager manager; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 Manager = Getloadermanager (); * * Click the button on the fragmentbutton, set the button's text to a edittext literal value in another fragment/public View Oncreateview (layoutinflater inflater, ViewGroup container, 
  Bundle savedinstancestate) {View view = Inflater.inflate (r.layout.list, NULL); 
 return view; 
  /** * Receives a callback function object, Callback.get (str) by invoking the method; * @param callBack */public void Set (CallBack callBack) {edittext edittext = (edittext) GetView (). Findviewbyid (R. 
  Id.name); 
 Callback.get (Edittext.gettext (). toString ()); 
 /* * Back off interface/* interface CallBack {public void get (String str); 

 } 
}

5.FragmentManage:
Fragmentmanager can achieve fragment in management activity. Gets an instance of it by invoking the Getfragmentmanager () of the activity.
Fragmentmanager can do the following things:
(1) using Findfragmentbyid () (for fragment that provide a UI in the activity layout) or Findfragmentbytag ()
(for fragment with or without UI) get the fragment that exists in the activity
(2) Pop the fragment from the background stack and use Popbackstack () (Simulate the user to press the back command).
(3) Register a listener that listens for background stack changes using Addonbackstackchangelistener ().

6.FragmentTransaction:
fragmenttransaction Add, remove, replace, and perform other actions on fragment.
Get an example of a fragmenttransaction from Fragmentmanager:

Fragmentmanager Fragmentmanager = Getfragmentmanager (); 
Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();

Each transaction is a set of changes to be executed at the same time. You can set all the changes you want to perform in a given transaction, using such things as add (), remove (), and replace (). Then, to apply a transaction to the activity, a commit () must be invoked.

Before you invoke commit (), you may want to invoke Addtobackstack () to add the transaction to the back stack of a fragment transaction. This back stack is managed by the activity and allows the user to return to the previous fragment state by pressing the down button.

For example, here's how to replace one fragment with another and keep the previous state in the background stack:

Create new fragment and transaction 

fragment newfragment = new Examplefragment (); 

Fragmenttransaction transaction = Getfragmentmanager (). BeginTransaction (); 

 Replace whatever is in the Fragment_container view with this fragment, 

//and add the transaction to the back stack Transaction.replace (R.id.fragment_container, newfragment); Transaction.addtobackstack (null); 

Commit the transaction transaction.commit ();

In this example, Newfragment replaces the fragment identified by the R.id.fragment_container in the current layout container. By invoking Addtobackstack (), the Replace transaction is saved to the back Stack so that the user can roll back the transaction and return to the previous fragment by pressing the back key.

If you add multiple changes to a transaction (such as add () or remove ()) and call Addtobackstack (), and the changes to all applications before you call commit () are added as a single transaction to the background stack, the back button returns them together.

The order in which changes are added to Fragmenttransaction is not important except for the following exceptions:
The commit () must be last called.
If you add multiple fragment to the same container, the order in which they are added determines the order in which they appear in the view hierarchy.
When a transaction that removes fragment is executed, if Addtobackstack () is not invoked, the fragment is destroyed when the transaction is committed, and the user cannot navigate back to it. In view of this, when a fragment is removed, if the Addtobackstack () is invoked, then fragment is stopped, and if the user navigates back, it will be restored.

Tip: For each fragment transaction, you can apply a transaction animation by invoking the settransition () implementation before committing the transaction.

Calling commit () does not immediately execute a transaction. On the contrary, it arranges transactions and, once ready, runs on the UI thread of the activity (the main thread). If necessary, at any rate, you can call from your UI thread Executependingtransactions () to immediately execute the transaction committed by commit (). But this is usually not necessary unless the transaction is a subordinate to a job in another thread.

Warning: You can only commit a transaction using commit () before the activity saves its state (when the user leaves the activity).

If you attempt to commit after that point, an exception is thrown. This is because if the activity needs to be recovered, the state after the commit may be lost. For situations where you feel you can lose submissions, use Commitallowingstateloss ().

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.