Android Basic Notes (18)-Fragment

Source: Internet
Author: User

    • The end of the blog's sentiment-start
    • What is Fragment
    • Two ways to add fragment to activity
    • The life cycle of fragment
    • Fragment Backwards-compatible
    • Communication between the fragment

Blog sentiment, end-start

This is the foundation of the last blog, learning a lot, there are many feelings.

Here is a general summary.

Persistence is often difficult, and perfect persistence is harder. This is the sentiment of writing these 18 blog posts.

Time drains quickly, always feel the time is not enough. Slowly will make the quality of their blog down. Today I think about it, I am making "broken windows"? (The broken window theory does not know can go to see)

Write to the 18th article, feel a lot of confusion, sure enough to see "knowledge points" and organizational language description "knowledge point" or there is a very poor difference.

This is the foundation of the last blog, that is an end, is also a beginning. The end is their own not serious attitude, the beginning is the new Android journey.

Learning, technology is endless. From today, we urge ourselves to be earnest, earnest and earnest.

Opportunity may come to you, but if you don't have the hard sweat before, you can't catch it.

What is Fragment

Fragment it was introduced at Android3.0, and is primarily used on large-screen devices to support dynamic and more flexible UI designs such as tablets.

Fragment is a behavior or part of the UI that manifests activity. Fragment can be imagined as a modular area of activity, with its own life cycle, receiving its own input events, and can be added and removed during activity operation (a bit like a "child activity" that can be reused in different activity ”)。

Fragment must be embedded in an activity. Their life cycles are directly affected by the life cycle of their host activity. When an activity is running, it is possible to operate each fragment independently, such as adding or removing them.

Fragment can define its own layout, lifecycle callback method so that fragment can be reused in multiple activity, so you can change the fragment combination depending on the screen size or use.

Two ways to add fragment to activity
One way, insert <fragmetn> as a child element of the layout, you can follow these steps:

① adds a label to the layout file <fragment> and specifies that the android:name property is an inherited Fragment 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:orientation  =;     <fragmentandroid:id= "@+id/list"android:name=" Com.bzh.layout.Fragment1 "android:layout_width="0dp "android:layout_height=" Match_parent "android:layout_weight=" 1 " />                                        </linearlayout>

② creates Fragment an inherited class and overrides the onCreateView() method in which it uses the inflate.inflate(R.layout.fragment1,null) XML file to generate a view object as the root layout of the fragment

publicclass Fragment1  extends Fragment{    @Override    publiconCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        null);        return view;    }}

③ creating a layout file named Fragment1

<?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:orientation="vertical" >                <TextViewandroid:layout_width="Match_parent"android:layout_ Height="Match_parent"android:text="I am Fragment1" />                        </linearlayout>

The results are as follows:

The steps for using elements directly in a layout file <fragment> are relatively simple, but can be seen or not flexible, and are not used in real-world use.

In addition, each fragment requires a unique identity, and if the activity restarts, the system can be used to recover the fragment, and the ID can be used to capture the fragment to handle the transaction, such as removing it. There are 3 ways to provide an ID for a fragment:
Use the Android:id property to provide a unique ID;
Use the Android:tag property to provide a unique string;
If none of the
above 2 you have provided, the system will use the ID of the container view;
Mode two, add or replace the fragment in the existing layout using the encoded method ViewGroup .
and the first way, we still need to prepare an inherited Fragment class, and prepare a layout file for it, in the onCreateView() callback, use the shim to return its instance as the layout.

The difference is that if you add or replace dynamically, we need to use the FragmentManager class, open the transaction, and, of course, commit the transaction.

windowmanager wm = (WindowManager) getsystemservice (window_service); int  height = wm.getdefaultdisplay (). GetHeight (); int  width = Wm.getdefaultdisplay (). GetWidth (); //get fragment manager  Fragmentmanager Fragmentmanager = Getfragmentmanager (); //Open transaction  Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction (); if  (Height > width) {//uses fragment to replace the specified layout  fragmenttransaction.replace (Android. R.id.content, new  Fragment1 ());} else  {//uses fragment to replace the specified layout  fragmenttransaction.replace (Android. R.id.content, new  Fragment2 ());} //Commit transaction  fragmenttransaction.commit (); 
The life cycle of fragment
The life cycle of the fragment is similar to the activity life cycle.
Onattach: Binding to activity
onCreate: Create fragment
Oncreateview: Creating a Fragment layout
onactivitycreated:activity After the creation is complete
OnStart: Visible, non-interactive
onresume: Visible,
interoperable
onPause: Partially visible, non-interactive
onStop: not visible
Ondestroyview: Destroying the Fragment View object
Ondestroy:fragment destroyed the
Ondetach: Unbind from Activity
In the actual development, of course not all rewrite, Google recommends that we at least rewrite three methods:
onCreate () We can initialize some of the components when fragment is created.
Oncreateview () when the Fragmetn interface is drawn for the first time, we must return a View object as the root layout of the FRAGMETN.
OnPause () when fragment is not able to interact with the user.
Fragment Backwards-compatible
Fragment was launched on Android 3.0, and if you want to use fragment in a low version of 3.0, you need to perform the following 2 steps:
change all fragment and Fragmentmanager to the class under the SUPPORT-V4 package.
change the activity's inheritance to fragmentactivity (under the SUPPORT-V4 package)
Communication between the fragment

The communication between the two fragment is mainly by Fragment setting a tag for the object, and using the FragmentManager.findFragmentByTag() method to find the object for the tag, so as to Fragment achieve the purpose of communication.

The following is a small case to use. In the main layout, there are two LinearLayout layouts left and right in the code, respectively, Fragment1 and filled in Fragment2 . Fragment1it contains a Button content that can be modified Fragment2 TextView .

First, replace the two fragment in the mainactivity with the specified layout.

LinearLayout ll1 = (LinearLayout) findViewById(R.id.ll1);LinearLayout ll2 = (LinearLayout) findViewById(R.id.ll2);FragmentManager fm = getFragmentManager();FragmentTransaction ft = fm.beginTransaction();// 给Fragment1对象设置tag为fragment1new Fragment1() ,"fragment1");// 给Fragment1对象设置tag为fragment2new"fragment2");ft.commit();

In Fragment2, we need to expose to the outside world how to modify TextView content, and it's simple:

 Public  class Fragment2 extends Fragment {    PrivateTextView TV;@Override     PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment2,NULL); TV = (TextView) View.findviewbyid (r.id.tv);returnView }//Exposure to the outside world to modify the TextView method     Public void Settextview(String content)    {tv.settext (content); }}

The next thing is very simple, in the Fragment1, according to tag to find Fragment2 object, and then modify the OK.

 Public  class Fragment1 extends Fragment {    @Override     PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment1,NULL);        Button btn = (button) View.findviewbyid (R.ID.BTN); Btn.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {//Use the Fragment Manager to find the object with tagFragment2 F2 = (Fragment2) Getfragmentmanager (). Findfragmentbytag ("Fragment2"); F2.settextview ("I'm going to your sister's."); }        });returnView }}

Android Basic Notes (18)-Fragment

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.