Android Fragment is completely parsed. Everything you need to know about Fragment,

Source: Internet
Author: User

Android Fragment is completely parsed. Everything you need to know about Fragment,

We all know that the interface display on Android is implemented through Activity, which is too common. I believe everyone is familiar with it and I will not repeat it here.

However, Activity also has its limitations. The same interface may be nice to display on the mobile phone, but it may not be good on the tablet, because the screen of the tablet is very large, when the mobile phone interface is placed on the tablet, it may be overly stretched, and the control spacing is too large. In this case, the better experience is to embed "small Activity" in the Activity, and then each "small Activity" can have its own layout. Therefore, Fragment, the main character of Alibaba Cloud, is on stage today.

Fragment

In order to make the interface better displayed on the tablet, Android 3.0 introduces the Fragment function, which is very similar to Activity and can contain layout like Activity. Fragment is usually used in nested activities. Now imagine this scenario: There are two Fragment, Fragment 1 contains a ListView, and each row displays the title of a book. Fragment 2 contains TextView and ImageView to display the detailed content and image of the book.

If the program is currently running in portrait mode on a tablet or mobile phone, Fragment 1 may be embedded in one Activity, and Fragment 2 may be embedded in another Activity, as shown in:

If the program is currently running on a horizontal screen tablet, two Fragment instances can be embedded in the same Activity, as shown in:

From this we can see that using Fragment allows us to make full use of the screen space of the tablet. Next we will explore how to use Fragment together.

First note that Fragment was introduced in version 3.0. If you are using a system earlier than version 3.0, You need to first import the jar package of the android-support-v4 to use the Fragment function.

Create a project named Fragments and create a layout file named fragment1.xml in the layout Folder:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#00ff00" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="This is fragment 1"        android:textColor="#000000"        android:textSize="25sp" /></LinearLayout>

As you can see, this layout file is very simple. There is only one LinearLayout, and a TextView is added to it. Let's create another fragment2.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#ffff00" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="This is fragment 2"        android:textColor="#000000"        android:textSize="25sp" /></LinearLayout>

Create a new class Fragment1, which inherits from Fragment:

public class Fragment1 extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.fragment1, container, false);    }}

We can see that this class is also very simple. It mainly loads the fragment1.xml layout file we just wrote and returns it. In the same way, let's write Fragment2 again:

public class Fragment2 extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.fragment2, container, false);    }}

Open or create activity_main.xml as the layout file of the main Activity, add two Fragment references to it, and use the android: name prefix to reference the specific Fragment:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:baselineAligned="false" >    <fragment        android:id="@+id/fragment1"        android:name="com.example.fragmentdemo.Fragment1"        android:layout_width="0dip"        android:layout_height="match_parent"        android:layout_weight="1" />    <fragment        android:id="@+id/fragment2"        android:name="com.example.fragmentdemo.Fragment2"        android:layout_width="0dip"        android:layout_height="match_parent"        android:layout_weight="1" /></LinearLayout>

Now we can run the program once, and we can see that an Activity contains two Fragment elements, which divide the entire screen equally, as shown below:

Add Fragment dynamically

You have learned how to use Fragment in XML, but this is only the simplest function of Fragment. Fragment is really powerful in that it can be dynamically added to the Activity, so this is something you must master. When you learn to add Fragment to the Activity while the program is running, the interface of the program can be customized more diverse. Now let's take a look at how to dynamically add Fragment.

Modify the Code on the basis of the previous section, open activity_main.xml, delete all references to Fragment, only keep the LinearLayout of the outermost layer, and add an id to it, because we need to dynamically add Fragment without adding it in XML, the code after deletion is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/main_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:baselineAligned="false" ></LinearLayout>

Open MainActivity and modify the Code as follows:

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Display display = getWindowManager().getDefaultDisplay();        if (display.getWidth() > display.getHeight()) {            Fragment1 fragment1 = new Fragment1();            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();        } else {            Fragment2 fragment2 = new Fragment2();            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();        }    }}

First, we need to get the width and height of the screen, and then judge, if the screen width is greater than the height, add fragment1, if the height is greater than the width, add fragment2. Dynamic Fragment addition is mainly divided into four steps:

1. Get the FragmentManager, which can be obtained directly through getFragmentManager in the Activity.

2. Start a transaction by calling the beginTransaction method.

3. Add Fragment to the container, which is generally implemented using the replace method. You need to input the container id and Fragment instance.

4. Submit the transaction and call the commit method to submit the transaction.

Run the program, as shown in the following figure:

If you are running on a simulator, press ctrl + F11 to switch to portrait mode. Shows the effect:

Fragment Lifecycle

Like Activity, Fragment also has its own lifecycle. It is very important to understand the lifecycle of Fragment. We can look at the lifecycle of Fragment through code:

public class Fragment1 extends Fragment {    public static final String TAG = "Fragment1";    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        Log.d(TAG, "onCreateView");        return inflater.inflate(R.layout.fragment1, container, false);    }    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        Log.d(TAG, "onAttach");    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.d(TAG, "onCreate");    }    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        Log.d(TAG, "onActivityCreated");    }    @Override    public void onStart() {        super.onStart();        Log.d(TAG, "onStart");    }    @Override    public void onResume() {        super.onResume();        Log.d(TAG, "onResume");    }    @Override    public void onPause() {        super.onPause();        Log.d(TAG, "onPause");    }    @Override    public void onStop() {        super.onStop();        Log.d(TAG, "onStop");    }    @Override    public void onDestroyView() {        super.onDestroyView();        Log.d(TAG, "onDestroyView");    }    @Override    public void onDestroy() {        super.onDestroy();        Log.d(TAG, "onDestroy");    }    @Override    public void onDetach() {        super.onDetach();        Log.d(TAG, "onDetach");    }}

As you can see, the above Code prints logs in each lifecycle method, and then we can run the program to see the print log as follows:

 

Click the home Key to print the log as follows:

If you re-enter the program, print the following log:

Click back to exit the program and print the following logs:

I believe most of my friends have understood this because it is similar to the Activity lifecycle. There are only a few new methods not available in the Activity. here we need to focus on the introduction:

 

  • OnAttach method: called when Fragment and Activity are associated.
  • OnCreateView method: called when layout is loaded for Fragment.
  • OnActivityCreated method: This method is called after the onCreate method in the Activity is executed.
  • OnDestroyView method: called when the layout in Fragment is removed.
  • OnDetach method: called when Fragment and Activity are unbound.

Communication between Fragment

Generally, an Activity contains multiple Fragment. How to communicate with multiple Fragment is a very important issue. Let's take an example to see how to access the view of another Fragment in one Fragment.

Modify the Code on the basis of the first section. First open fragment2.xml and add a button in the layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:background="#ffff00" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="This is fragment 2"        android:textColor="#000000"        android:textSize="25sp" />        <Button         android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Get fragment1 text"        /></LinearLayout>

Open fragment1.xml and add an id for TextView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#00ff00" >    <TextView        android:id="@+id/fragment1_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="This is fragment 1"        android:textColor="#000000"        android:textSize="25sp" /></LinearLayout>

Next, open Fragment2.java, add the onActivityCreated method, and process the Click Event of the button:

public class Fragment2 extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.fragment2, container, false);    }    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        Button button = (Button) getActivity().findViewById(R.id.button);        button.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);                Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();            }        });    }}

Run the program and click the button on fragment2. The result is as follows:

 

We can see that the view in fragment1 is successfully obtained in fragment2, and Toast is displayed. How is this implemented? It is mainly implemented through the getActivity method. The getActivity method allows Fragment to obtain the associated Activity, and then call the findViewById method of the Activity to obtain other Fragment views associated with the Activity.

Well, the above is everything you need to know about Fragment. If you want to learn more about Fragment, read the Android mobile phone flat. Use Fragment to implement apps compatible with mobile phones and tablets and Android Fragment applications. Use Fragment to say goodbye to ActivityGroup.

 

Reproduced in: http://blog.csdn.net/guolin_blog/article/details/8881711

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.