"android app Development technology: application components" fragment how to use

Source: Internet
Author: User
<span id="Label3"></p><p><p>Guo Xiaoxing<br>Weibo: Guo Xiaoxing's Sina Weibo<br>Email:<span class="__cf_email__" data-cfemail="03626f6f666d74666f6f70433235302d606c6e">[email protected]</span><br>Blog: Http://blog.csdn.net/allenwells<br>Github:https://github.com/allenwells</p></p>A fragment management and business<p><p>Activity through Fragmentmanager management Fragment,fragmentmanager can accomplish the following functions:</p></p> <ul> <ul> <li>Call the Findfragmentbyid () or Findfragmentbytag () method to get the specified Fragment. When you define fragment in an XML file, you can identify fragment by Android:id or Android:tag.</li> <li>Call the Popbackstack () method to eject the fragment from the background stack and impersonate the User's back key.</li> <li>Call Addonbackstackchangelistener () to register a listener to listen for changes in the background stack.</li> </ul> </ul><p><p>Before learning how to create fragment, let's take a look at Fragment's inheritance system, as shown in:</p></p><p><p>Fragment inheritance System class diagram Visio source file download</p></p><p><p></p></p><p><p>Creating a fragment only requires inheriting the fragment class, and then writing the business logic in the corresponding life cycle method. When we define a fragment, the most commonly overridden method is Oncreateview (), as Follows:</p></p><pre class="prettyprint"><code class=" hljs java"><code class="hljs java"><span class="hljs-keyword">import </span> android.os.Bundle; <span class="hljs-keyword">import </span> android.support.v4.app.Fragment; <span class="hljs-keyword">import </span> android.view.LayoutInflater; <span class="hljs-keyword">import </span> android.view.ViewGroup; <span class="hljs-keyword">public </span> <span class="hljs-class"><span class="hljs-keyword">class </span> <span class="hljs-title">articlefragment </span> <span class="hljs-keyword">extends </span> <span class="hljs-title">fragment </span> {</span> <span class=" Hljs-annotation "> @Override </span> <span class=" hljs-keyword ">public </span> View <span class=" hljs-title "> Oncreateview </span> (layoutinflater inflater, viewgroup container, Bundle savedinstancestate) {<span class=" Hljs-comment ">//inflate The layout for this fragment </span> <span class=" hljs-keyword ">return </span> INFLATER.INFL Ate (r.layout.article_view, container, <span class="hljs-keyword">false </span>); }}</code></code></pre>1.1 Add Fragment1.1.1 static add<p><p>The so-called static add is the total use of elements in the layout file, the Android:name attribute of the element specifies the class that implements the Fragment. This method of using an XML layout file to add fragment statically to the activity, fragment, cannot be dynamically removed. If you want to implement Fragment's dynamic cut-in and cut-out, then you need to add fragment to the activity after the activity is Started.</p></p><p><p><strong>Example</strong></p></p><p><p>Define a Res/layout-large/news_articles.xml file</p></p><pre class="prettyprint"><code class=" hljs xml"><span class="hljs-tag"><span class="hljs-tag"><<span class="hljs-title">linearlayout</span> <span class="hljs-attribute">xmlns:android</span>=<span class="hljs-value">"http://schemas.android.com/apk/res/android"</span> <span class="hljs-attribute"> Android:orientation</span>=<span class="hljs-value">"horizontal"</span><span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"fill_parent"</span><span class="hljs-attribute">android: Layout_height</span>=<span class="hljs-value">"fill_parent"</span>> </span></span> <span class="hljs-tag"><span class="hljs-tag"><<span class="hljs-title">fragment </span> <span class="hljs-attribute">android:name </span> =<span class="hljs-value"> "com.example.android.fragments.HeadlinesFragment" </span> <span class="hljs-a Ttribute ">android:id </span> =<span class=" hljs-value ">" @+id/headlines_fragment "</span> <span class=" Hljs-attri Bute ">android:layout_weight </span> =<span class=" hljs-value ">" 1 "</span> <span class=" hljs-attribute ">android:l Ayout_width </span> =<span class="hljs-value"> "0dp" </span> <span class="hljs-attribute">android:layout_height <!-- Span-->=<span class="hljs-value"> "match_parent" </span>/> </span></span></span> <span class="hljs-tag"><span class="hljs-tag"><<span class="hljs-title">fragment</span> <span class="hljs-attribute">android:name</span>=<span class="hljs-value">"com.example.android.fragments.ArticleFragment"</span> <span class="hljs-attribute"> Android:id</span>=<span class="hljs-value">"@+id/article_fragment"</span><span class="hljs-attribute">android:layout_weight</span>=<span class="hljs-value">"2"</span><span class="hljs-attribute">android:layout_ Width</span>=<span class="hljs-value">"0dp"</span><span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"match_parent"</span> /> </span></span><span class="hljs-tag"><span class="hljs-tag"></<span class="hljs-title">linearlayout</span>></span></span></code></pre><p><p>Add a layout file to an activity</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword">import</span> android.os.Bundle;<span class="hljs-keyword">import</span> android.support.v4.app.FragmentActivity;<span class="hljs-keyword">public</span><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">FragmentActivity</span> {</span> <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span><span class="hljs-keyword">void</span><span class="hljs-title">onCreate</span>(Bundle savedInstanceState) { <span class="hljs-keyword">super</span>.onCreate(savedInstanceState); setContentView(R.layout.news_articles); }}</code></pre></pre>1.1.2 Dynamic Additions<p><p>Add fragment in Java code through the Add () method of the Fragmenttransaction Object. The Activity's Getfragmentmanager () method returns the Fragmentmanager object, Fragmentmanager the Object's begintransaction () method to turn on and return the Fragmenttransaction Object.</p></p><p><p><strong>Example</strong></p></p><p><p>Define a Res/layout_articles.xml file</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs xml"><span class="hljs-tag"><<span class="hljs-title">FrameLayout</span> <span class="hljs-attribute">xmlns:android</span>=<span class="hljs-value">"http://schemas.android.com/apk/res/android"</span> <span class="hljs-attribute">android:id</span>=<span class="hljs-value">"@+id/fragment_container"</span> <span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"match_parent"</span> <span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"match_parent"</span> /></span></code></pre></pre>1.2 Replacing fragment<p><p>The process of replacing fragment is very similar to the process of adding, and it is necessary to replace the Add () method with the replace () Method.</p></p><p><p><strong>Note</strong> : When we perform fragment transactions, such as replacements, we need to allow the user to navigate backwards and undo the operation, in order to allow the user to navigate backwards fragment transactions, We need to call the Addtobackstack () method before Fragmenttransaction Commits. The Addtobackstack () method provides an optional string parameter that specifies a unique name for the Transaction. This name is not required unless we intend to use Fragmentmanager.backstackentry APIs for some advanced fragment Operations.</p></p><p><p>When we remove or replace a fragment and put it into the return stack, the life cycle of the removed fragment is stopped, not Destoryed. When the user returns to restore the fragment, its life cycle is restarts. If we do not put fragment into the return stack, then when it is removed or replaced, its life cycle is Destoryed.</p></p><p><p><strong>Example</strong></p></p><pre class="prettyprint"><pre class="prettyprint"><code class="language-java hljs "><span class="hljs-comment">// Create fragment and give it an argument specifying the article it should show</span><span class="hljs-keyword">new</span><span class="hljs-keyword">new</span> Bundle();args.putInt(ArticleFragment.ARG_POSITION, position);newFragment.setArguments(args);FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();<span class="hljs-comment">// Replace whatever is in the fragment_container view with this fragment,</span><span class="hljs-comment">// and add the transaction to the back stack so the user can navigate back</span>transaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(<span class="hljs-keyword">null</span>);<span class="hljs-comment">// Commit the transaction</span>transaction.commit();</code></pre></pre>Two fragment and activity communication<p><p>First of all, Let's talk about the interaction between the two Fragment.</p></p><p><p>In order to reuse the fragment UI components, we should build each fragment into fully self-contained, modular components that define their own layout and Behavior. When we define these modular fragment, we can associate them with activity so that they are combined with the logic of the app to achieve a global composite ui.</p></p><p><p>In general, we want fragment to interact with each other, such as changing fragment content based on user Events. <strong>the interaction between all fragment needs to be through their associated activity, and the two fragment should not interact directly with each other. </strong></p></p>2.1 Activity transmits data to fragment<p><p>Create bundle packets in activity and call Fragment's setarguments (bundle Bundle) method to pass bundle packets to Fragment.</p></p><p><p><strong>Example</strong></p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">Static</span></span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">class</span> <span class="hljs-title">mainactivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span><span class="hljs-keyword"></span> implements <span class="hljs-title"> Headlinesfragment</span>. <span class="hljs-title">Onheadlineselectedlistener</span> { </span></span>...<span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onarticleselected</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Position) {<span class="hljs-comment"><span class="hljs-comment">//the user selected the headline</span> of a article from the Headlinesfragment</span> <span class="hljs-comment"><span class="hljs-comment">//do something</span> here to display that article</span>Articlefragment Articlefrag = (articlefragment) Getsupportfragmentmanager (). Findfragmentbyid (R.id.article_f ragment);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(articlefrag! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//If Article Frag is available, we ' re in Two-pane layout ...</span></span> <span class="hljs-comment"><span class="hljs-comment">//call A method</span> in the articlefragment to update its content</span>Articlefrag.updatearticleview (position); }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span>{<span class="hljs-comment"><span class="hljs-comment">//Otherwise, we ' re in the One-pane layout and must swap frags ...</span></span> <span class="hljs-comment"><span class="hljs-comment">//Create fragment and give it an argument for the selected article</span></span>Articlefragment newfragment =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Articlefragment (); Bundle args =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Bundle (); Args.putint (articlefragment.arg_position, POSITION); Newfragment.setarguments (args); Fragmenttransaction transaction = Getsupportfragmentmanager (). begintransaction ();<span class="hljs-comment"><span class="hljs-comment">//Replace Whatever is in the Fragment_container view with this fragment,</span></span> <span class="hljs-comment"><span class="hljs-comment">//and Add the transaction</span> to the back stack so the user can navigate back</span>Transaction.replace (r.id.fragment_container, newfragment); Transaction.addtobackstack (<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>);<span class="hljs-comment"><span class="hljs-comment">//Commit The transaction</span></span>Transaction.commit (); } }}</code></pre>2.2 Fragment data transfer to activity<p><p>Define an internal callback interface in fragment, and then let the activity that contains the fragment implement the callback interface so that fragment can invoke the callback method to pass the data to the Activity.</p></p><p><p><strong>Example</strong></p></p><p><p>An interface has been defined in fragment</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">class</span> <span class="hljs-title">headlinesfragment</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">listfragment</span> {</span></span>Onheadlineselectedlistener mcallback;<span class="hljs-comment"><span class="hljs-comment">//Container Activity must implement this interface</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">interface</span> <span class="hljs-title">onheadlineselectedlistener</span> {</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onarticleselected</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>position); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Onattach</span></span>(activity Activity) {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. Onattach (activity);<span class="hljs-comment"><span class="hljs-comment">//this makes sure, the container activity has implemented</span></span> <span class="hljs-comment"><span class="hljs-comment">//the Callback Interface. If not, It throws an exception</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Try</span></span>{mcallback = (onheadlineselectedlistener) activity; }<span class="hljs-keyword"><span class="hljs-keyword">Catch</span></span>(classcastexception E) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>ClassCastException (activity.tostring () +<span class="hljs-string"><span class="hljs-string">"must Implement onheadlineselectedlistener"</span></span>); } }<span class="hljs-comment"><span class="hljs-comment">//fragment sending information to the owning activity via callback interface</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Onlistitemclick</span></span>(ListView l, View v,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Position<span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Id) {<span class="hljs-comment"><span class="hljs-comment">//Send the event to the host activity</span></span>Mcallback.onarticleselected (position); }}</code></pre><p><p>The activity that the fragment belongs to implements the interface</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword">public</span><span class="hljs-keyword">static</span><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HeadlinesFragment</span>.<span class="hljs-title">OnHeadlineSelectedListener</span>{</span> ... <span class="hljs-keyword">public</span><span class="hljs-keyword">void</span><span class="hljs-title">onArticleSelected</span>(<span class="hljs-keyword">int</span> position) { <span class="hljs-comment">// The user selected the headline of an article from the HeadlinesFragment</span> <span class="hljs-comment">// Do something here to display that article</span> }}</code></pre></pre> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p> Android App Development technology: application components fragment how to use </p> </p></span>

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.