Basic overview of Fragments


Introduction to this section

Okay, in the previous chapter we put the four major components of Android: Activity, Service, BroadCastReceiver, ContentProvider As well as the bond between them: Intent, we have all played it out, and this chapter brings you a Fragment. In this section we will introduce some basic concepts and usage of this Fragment! Official document: Fragment


1. Basic concepts

1) What is it and what is it used for?

Answer: Fragment is a new API introduced after Android 3.0. Its original intention was to adapt to large-screen tablets. Of course, it is still the darling of tablet APP UI design, and our ordinary mobile phone development will also add this fragment. We can think of it as a small Activity, also called Activity fragment! Think about it, if a large interface, we With just one layout, it would be very troublesome to write the interface, and if there are many components, it would also be very troublesome to manage! Instead of using Fragment We can divide the screen into several pieces and then group them for modular management! This makes it more convenient to Dynamically update the activity's user interface during operation! In addition, Fragment cannot be used alone, it needs to be nested in Activity Used in, although it has its own life cycle, it will still be affected by the life cycle of the host Activity, such as Activity If it is destroyed by destroy, it will also be destroyed!

The following picture is a Fragment given in the document corresponding to different situations between mobile phones and tablets:

1.png

PS: Simple The news browsing page uses two Fragments to display the news list and news content respectively;


2) Fragment life cycle diagram

2.jpg


3) Core points:

Here are some key points of using Fragment:

  • Introduced after version 3.0, that is, minSdk must be greater than 11
  • Fragment needs to be nested in Activity. Of course, it can also be nested in another Fragment, but this one is nested The Fragment also needs to be nested in the Activity. Indirectly speaking, the Fragment still needs to be nested in the Activity!! Affected by the life cycle of the host Activity, of course it also has its own life cycle! In addition, it is not recommended to use it in Fragment. Nested Fragment because the life cycle of the Fragment nested inside is uncontrollable!!!
  • Official documents say that when creating a Fragment, at least three methods need to be implemented: onCreate(), onCreateView(), OnPause(); But it seems that it is possible to only write one onCreateView...
  • The life cycle of Fragment is somewhat similar to that of Activity: three states:
    Resumed: The Fragment that is allowed is visible
    Paused: The Activity where it is located is visible , but can’t get focus
    Stoped: ①Call addToBackStack() and the Fragment is added to the Bcak stack ②The Activity moves to the background, or the Fragment is replaced/deleted
    ps: The fragment in the stopped state is still alive (all status and member information are maintained by the system), however, it is not useful to the user It is no longer visible, and if the activity is killed, he will also be killed.

4) Several subclasses of Fragment:

ps: Many times we They all directly rewrite Fragment, inflate loads the layout to complete the corresponding business, subclasses are not used much, wait for the need Time to delve deeper!

  • Dialog:DialogFragment
  • List:ListFragment
  • Option settings :PreferenceFragment
  • WebView interface:WebViewFragment

5) Should you use the Fragment under the App package or v4? Under the package:

Problem overview:

I believe many friends will encounter the following situation when using Fragment:

3.jpg

So should we use the Fragment under android.app or the android.support.v4.app package? What about Fragments?

Answer: In fact, all are possible. As mentioned earlier, Fragment was introduced after Android 3.0 (API 11), so if the app developed requires What about running on versions below 3.0? For example, 2.3 still has a little market share! So, the v4 package came into being, And the minimum is compatible with version 1.6! As for which package to use, it all depends on your needs. Nowadays, the market share of mobile phones under 3.0 is actually very small. Suijie is all about 4.0 and above, and 6.0 will be released in October. What do you think... So at this time, you can directly Use Fragment under app package Then calling the relevant methods, there is usually no problem; if your Fragment uses the app package, Both FragmentManager and FragmentTransaction need to be in the app package! Either use app for all, or v4 for all, Otherwise, an error will be reported! Of course, if you want your app to be compatible with lower version mobile phones, then you can choose to use the v4 package!

Things to note when using Fragment under the v4 package:

  • ① If you use Fragment under the v4 package, then the Activity you are in must inherit FragmentActivity! Case: Today I statically loaded the fragment in the xml file, and then rewritten the fragment, but when loading the Activity, an error was reported. The general hint is that the Fragment error is still not found or something. The name attribute has been changed several times and it is still wrong! Finally I found out that I used Because of the v4 package, you only need to change your Activity to FragmentActivity!
  • ② I wrote the following code before, and then reported an error:

4.jpg

It’s a bit baffling. Fragment, FragmentManager, and FragmentTransaction all use the v4 package. Activity also inherits FragmentActivity? Just change it to the app package, but this is different from the v4 package we use. Is there a conflict in the premise? In fact, there is a solution?
Answer: Just change getFragmentManager( ) to getSupportFragmentManager( )


2. Create a Fragment

1) Static loading of Fragment

Implementation process:

5.png

Sample code:

Step 1:Define the layout of the Fragment, which is the display content of the fragment
Step 2 :To customize a Fragment class, you need to inherit Fragment or its subclass and override the onCreateView() method In this method, call: inflater.inflate() method to load the layout file of the Fragment, and then return the loaded view object

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

Step 3:Add the fragment tag in the layout file corresponding to the Activity that needs to load the fragment. Remember, the name attribute is a fully qualified class name, which means it must include the package name of the Fragment, such as:

<fragment
android:id="@+id/fragment1"
android:name="com.jay.example.fragmentdemo.Fragmentone"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

Step 4: Activity calls setContentView() in the onCreate() method to load the layout file!


2) Dynamically load Fragment

Implementation process:

7.png

##Sample code: What is demonstrated here is that when the horizontal and vertical screens are switched, the Switch Fragment:

6.gif

The Fragment and layout code will not be posted. Directly paste the key code of MainActivity:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display dis = getWindowManager() .getDefaultDisplay();
if(dis.getWidth() > dis.getHeight())
{
Fragment1 f1 = new Fragment1();
getFragmentManager().beginTransaction() .replace (R.id.LinearLayout1, f1).commit();
       }
         
                                                                                                                                                                RagmentManager().beginTransaction() .replace(R.id.LinearLayout1, f2).commit();
}
}  
}


3.Fragment management and Fragment transactions

8.png


4.Interaction between Fragment and Activity

9.png

Some friends may not like to see pictures, so let’s introduce it in words:

1) Component acquisition

Fragment gets the components in Activity: getActivity(). findViewById(R.id.list);
Activity gets the components in Fragment (either based on id or tag):getFragmentManager.findFragmentByid(R.id.fragment1);


2) Data transfer

①Activit passes data to Fragment:

Create a Bundle data package in Activity and call setArguments of Fragment instance (bundle) Thus, the Bundle data packet is passed to the Fragment, and then getArguments is called in the Fragment to obtain Bundle object, and then parse it

②Fragment passes data to Activity

Define an internal callback interface in Fragment, and then let it include The Fragment's Activity implements the callback interface. Fragment can transfer data through the callback interface. Callback, I believe many people know what it is, but I can't write it down. The "fragment transfers data to Activity" on the Internet is all the code written by Teacher Li Gang. I'm really speechless. Forget it, let’s just write down the partial code here. I believe readers will understand it at a glance:

Step 1: Define a callback interface: (in Fragment)

/*Interface*/
public interface CallBack{
/*Define a method to obtain information*/
public void getResult(String result);
}

Step 2: Interface callback (in Fragment)

/*Interface callback*/
public void getData(CallBack callBack){
/ *Get the information of the text box, of course you can also pass other types of parameters, depending on the needs*/
String msg = editText.getText().toString();
callBack.getResult(msg);
}

Step 3: Use the interface callback method to read data (in Activity)

/* Use the interface callback method to obtain data */
leftFragment.getData(new CallBack() {
@Override
public void getResult(String result) { /*Print information*/
Toast.makeText(MainActivity.this, "-->>" + result, 1) . show(); Define an abstract method in the interface, and set the type of data parameters you want to pass;

->
Then you also write an abstract method in the call interface to pass the data to be passed

->The next step is Activity. Call the method provided by Fragment, and then process the data when overriding the abstract method. Just read!!!③Data transfer between Fragment and Fragment

In fact, this is very simple, find the fragment to accept the data Object, just call setArguments directly to pass data in. Usually when replacing, that is, data is transferred when the fragment jumps, then you only need to initialize the Fragment to be jumped. Then call its setArguments method to pass in the data! If two Fragments need to transmit data immediately instead of jumping, you need to get the data passed by f1 in Activity first. Then it is passed to f2, using Activity as the medium~

The sample code is as follows:

FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();

Fragmentthree t1 = new Fragmentthree();
Fragmenttwo t2 = new Fragmenttwo();

Bundle bundle = new Bundle();bundle.putString(" key",id);t2.setArguments(bundle);

fTransaction.add(R.id.fragmentRoot, t2, "~~~");
fTransaction.addToBackStack(t1);
fTransaction.commit();


5. Take a walk through the life cycle diagram:

After much thought, I decided to take you through a simple life cycle diagram to deepen your understanding of the Fragment life cycle:

①When Activity loads Fragment, it calls the following methods in sequence: onAttach -> onCreate -> onCreateView -> onActivityCreated -> onStart ->onResume

②When we create a suspended dialog-style Activity, or other, it is where the Fragment is located Activity is visible, but does not get focusonPause

③When the dialog box is closed, Activity gains focus again:onResume

④When we replace Fragment , and call addToBackStack() to add him to the Back stackonPause -> onStop -> onDestoryView! ! Note, the Fragment at this time has not been destroyed yet!!!

⑤When we press the back key on the keyboard, the Fragment will be displayed again:onCreateView -> onActivityCreated -> onStart -> onResume

⑥If after we replace, the addToBackStack() method is not called before the transaction commit will If the Fragment is added to the back stack; or if the Activity is exited, the Fragment will be completely ended. Fragment will enter the destruction stateonPause -> onStop -> onDestoryView -> onDestory -> onDetach


Summary of this section:

This section explains to you some basic concepts and simple usage of the following Fragment. I believe you will gradually like it. superior Fragment, because of the length, I will write so much in this section. In the next section, we will take you to write something about Fragment. Commonly used examples, please stay tuned, thank you~