Two methods for creating Fragment in Android: androidfragment

Source: Internet
Author: User

Two methods for creating Fragment in Android: androidfragment

Fragment is an Activity or part of the user interface. You can combine multiple Fragment into a multi-region UI on a single Activity and use it in multiple activities. You can think of fragment as a module part of an activity. It has its own lifecycle, receives its own input events, and can be added or deleted when the Activity is running.

Two concepts: Fragment and host

The lifecycle of fragment is directly affected by the lifecycle of its host activity. For example, once an activity is paused, all fragment in it is also paused. Once an activity is destroyed, all fragment in it is also destroyed.

Android 3.0 (11) introduces the 7fragment Concept

With fragment, you do not have to manage complex changes in the view system. By dividing the actjvjty layout into several fragment, You can edit the activity presentation at runtime, and those changes will be saved in the background stack managed by the activity.

To create a fragment, you must create a subclass of fragment (or a subclass inherited from it ). The code of the fragment class looks like activity. It has callback functions like activity, such as onCreate (), onstart (), onPause (), and onstop (). In fact, if you are using a ready-made Android app instead of fragment, you can simply port the code from the activity callback function to their respective fragment callback functions.

In addition to the base class fragment, there are several subclasses that you may inherit:

DialogFragment, ListFragment, PreferenceFragment

Generally, you must implement at least the following lifecycle methods:

OnCreate ():This method is called when fragment is created. In the implementation code, you can initialize the necessary components that you want to maintain in fragment. After the fragment is paused or stopped, you can re-enable them.

OnCreateView ():This method is called when the user interface is drawn for fragment for the first time. Draw a user interface for fragment. This function must return the painted
The Root View of the fragment. If fragment does not have a user interface, it can return null.

OnPause ():The system will call this function as the first warning of the user's departure from fragment (although this does not always mean that fragment is destroyed ). Before the end of the current user session, it is usually necessary to submit any persistent changes here (because the user may not return any more ).

The following describes how to add fragment to an activity: (1) Declare fragment in the activity layout file (2) Add fragment to a saved ViewGroup using java code

 

Example:

 

The two colors distinguish two different fragment:

(1) Declare fragment in the activity layout File

Now we can declare the Left and Right fragment in the activity_main.xml file of layout to achieve the display effect.

Step 1: Create the layout file left_layout.xml (right_layout.xml) on the left (right) in layout:
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 3 android: orientation = "vertical" android: layout_width = "match_parent" 4 android: layout_height = "match_parent" 5 android: gravity = "center_horizontal" 6 android: background = "#6f6669"> 7 <Button 8 android: layout_width = "wrap_content" 9 android: layout_height = "wrap_content" 10 android: text = "pan Houye"/> 11 <Button12 android: layout_width = "wrap_content" 13 android: layout_height = "wrap_content" 14 android: text = "bikong sea"/> 15 </LinearLayout>
Step 2: Create the left_layout.xml (right_layout.xml) layout to inherit the java LeftFragment. java (RightFragment. java) class of Fragment)

LeftFragment. java file:

1 import android. app. fragment; 2 import android. OS. bundle; 3 import android. view. layoutInflater; 4 import android. view. view; 5 import android. view. viewGroup; 6/** 7 * Created by panchengjia on 2016/12/15. 8 */9 public class LeftFragment extends Fragment {10 @ Override11 public void onCreate (Bundle savedInstanceState) {12 super. onCreate (savedInstanceState); 13} 14 @ Override15 public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {16 // obtain the corresponding layout 17 View = inflater by filling the layout in the parameter. inflate (R. layout. left_layout, container, false); 18 return view; 19} 20 @ Override21 public void onPause () {22 super. onPause (); 23} 24}
Step 3: declare two fragment la s in the active layout file activity_main.xml in layout.
 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     xmlns:tools="http://schemas.android.com/tools" 4     android:id="@+id/activity_main" 5     android:layout_width="match_parent" 6     android:layout_height="match_parent" 7     android:orientation="horizontal" 8     tools:context="com.example.administrator.fragmenttest.MainActivity"> 9     <fragment10         android:layout_width="0dp"11         android:layout_height="match_parent"12         android:layout_weight="1"13         android:name="com.example.administrator.fragmenttest.LeftFragment"14         tools:layout="@layout/left_layout" />15     <fragment16         android:layout_width="0dp"17         android:layout_height="match_parent"18         android:layout_weight="3"19         android:name="com.example.administrator.fragmenttest.RightFragment"20         tools:layout="@layout/right_layout" />21 </LinearLayout>
(2) Add fragment to the existing ViewGroup using java code

Here we will demonstrate adding fragment (right_layout.xml) On the right side to the viewgroup of the main layout through java code.

The knowledge points used to add fragment through code are summarized as follows:

To manage fragment in an activity, you can use FragmentManager. You can obtain it by calling getFragmentManager () in the activity. You can use FragmentManager to do the following, including:

1. Use findFragmentByld () (used to provide fragment with interfaces in the activity layout) or fjndFragmentByTag () to obtain fragment existing in the activity (used for fragment with or without interfaces ).

2. Use popBackstack () to pop up fragment from the background stack (imitating the user's BACK command.

3. Use addonBackstackChangedListener () to register a listener that listens to background stack changes.

A major feature of fragment in an activity is its ability to add, delete, replace, and execute other actions to respond to user interactions. Every change committed to the activity is called a transaction and can be processed using APIs in FragmentTransactjon.

The knowledge points used here are marked in the code. You can view the API documentation to learn more about the extended usage.

Step 1: The activity_main2.xml file of the main Layout in Layout (the left fragment Layout is directly declared in the Layout, and the right fragment is implemented by filling in the code in FrameLayout ):
 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     xmlns:tools="http://schemas.android.com/tools" 4     android:id="@+id/activity_main2" 5     android:layout_width="match_parent" 6     android:layout_height="match_parent" 7     android:orientation="horizontal" 8     tools:context="com.example.administrator.fragmenttest.Main2Activity"> 9     <fragment10         android:layout_width="0dp"11         android:layout_height="match_parent"12         android:layout_weight="1"13         android:name="com.example.administrator.fragmenttest.LeftFragment"14         tools:layout="@layout/left_layout" />15     <FrameLayout16         android:id="@+id/right"17         android:layout_width="0dp"18         android:layout_height="match_parent"19         android:layout_weight="3"></FrameLayout>20 </LinearLayout>
Step 2: in Java, the Main2Activity. java corresponding to the main layout adds fragment to the main layout ViewGroup through code:
1 import android. app. fragmentManager; 2 import android. app. fragmentTransaction; 3 import android. support. v7.app. appCompatActivity; 4 import android. OS. bundle; 5 public class Main2Activity extends AppCompatActivity {6 // declare the java class 7 FragmentManager fragmentManager used this time; 8 FragmentTransaction fragmentTransaction; 9 RightFragment rightFragment; 10 @ Override11 protected void onCreate (Bundle savedInstanceState) {12 super. onCreate (savedInstanceState); 13 setContentView (R. layout. activity_main2); 14/* Get the FragmentManager through getFragmentManager () 15 * in the corresponding java class of the activity, used to manage the fragment16 **/17 fragmentManager = getFragmentManager () in ViewGrop (); 18/* FragmentManager to manage a series of transaction changes of fragment (ADD, replace and other execution actions) 19 *, you need to use fragmentTransaction to execute 20 */21 fragmentTransaction = fragmentManager. beginTransaction (); 22 // instantiate the fragment23 rightFragment = new RightFragment (); 24 // Add the fragment to the corresponding layout by adding (Transaction Processing) 25 fragmentTransaction. add (R. id. right, rightFragment); 26 // after the transaction is processed, 27 fragmentTransaction needs to be submitted. commit (); 28} 29}

Today, the interaction between fragmen and activity is described in detail later. I went to bed early.

 

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.