Android learning - fragments (fragment)

1. What is Fragmentation

Fragment is a new API introduced after Android 3.0. Its original intention is to adapt to large-screen tablet computers. Of course, it is still the darling of tablet APP UI design, and we will also add this Fragment to ordinary mobile phone development. We It can be regarded as a small Activity, also known as an Activity fragment!

The picture below is a processing picture of a fragment corresponding to a mobile phone and a tablet respectively.
insert image description here

2. How to use fragments

2.1 Statically loading Fragment

Step 1:
Define a Fragment xml file

What I defined is left_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/button"
        android:text="Button"
        />

</LinearLayout>

Step 2:
Customize a Fragment class, you need to inherit Fragment or its subclasses, rewrite the onCreateView() method,
call in this method: inflater.inflate() method loads the layout file of Fragment, and then returns the loaded view object

  • When inheriting Fragment, there will be two Fragments under different packages for us to choose (as shown in the figure below).
    insert image description here
    One is androidx.fragment.app.Fragment in the AndroidX library, and the other is the built-in android.app.Fragment of the system. Here we choose AndroidX Fragment in the library, because it can make the characteristics of Fragment consistent in all Android system versions, and the built-in Fragment of the system has been abandoned in Android 9.0 version.
//这里的名字就叫LeftFragment
public class LeftFragment extends Fragment {
    
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    
    
        View view=inflater.inflate(R.layout.left_fragment,container,false);
        return view;
    }
}

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

<fragment
    android:id="@+id/left_fragment"
    android:name="com.example.fragmenttest.LeftFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

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

2.2 Dynamically add fragments

Implementation process
insert image description here

2.3 Return stack in fragment

We have successfully implemented the function of dynamically adding fragments to the activity, but if you try it, you will find that after you add a fragment by clicking the button, press the Back key and the program will exit directly. If we want to imitate the effect similar to returning to the stack, press the Back key to return to the previous fragment, how to achieve it?
In fact, it is very simple. FragmentTransaction provides an addToBackStack() method, which can be used to add a transaction to the return stack and modify the code in MainActivity, as shown below.

private void replaceFragment(Fragment fragment) {
    
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

2.4Fragment management and Frangment affairs

insert image description here

2.5 Interaction between Fragment and Activity

insert image description here

  1. component acquisition

Fragment gets components in Activity: getActivity().findViewById(R.id.list);
Activity gets components in Fragment (according to id and tag): getFragmentManager.findFragmentByid(R.id.fragment1);

  1. Data transfer
    ①Activity transfers data to Fragment:

    Create a Bundle data package in the Activity, call setArguments(bundle) of the Fragment instance to pass the Bundle data package to the Fragment, and then call getArguments in the Fragment to obtain the Bundle object, and then parse it.

    ②Fragment transfers data to Activity

    1. Define an interface in Fragment, define an abstract method in the interface, and set the type of data parameter you want to pass; 2.
    Then write an abstract method to call the interface, and pass the data to be passed
    3. Then It is Activity, call the method provided by Fragment, and then read the data when rewriting the abstract method!!!

    ③Data transfer between Fragment and Fragment

    Find the fragment object to receive data, and call setArguments directly to pass the data in.
    Usually, when replacing, that is, when the fragment jumps, the data is passed. Then you only need to call its setArguments method after initializing the Fragment to be jumped. Just enter the data!
    If two Fragments need to transmit data immediately instead of jumping, you need to obtain the data transmitted by f1 in the Activity first, and then transmit it to f2, which is to use the Activity as the medium

3. Fragment life cycle

3.1 The status of fragments

  1. Running state
    A fragment is running when it is visible and its associated activity is running.
  2. Suspended state
    When an activity enters the suspended state (because another activity that does not fill the screen is added to the top of the stack), the visible fragment associated with it enters the suspended state.
  3. Stopped state
    When an activity enters the stopped state, the fragments associated with it will enter the stopped state, or the fragments will be removed from the activity by calling the remove() and replace() methods of FragmentTransaction , but if the transaction is committed before Call the addToBackStack() method, and the fragments will also enter the stop state at this time. In general, fragments that enter the stopped state are completely invisible to the user and may be recycled by the system.
  4. Destroyed state
    fragments always exist attached to the activity, so when the activity is destroyed, the fragments associated with it will enter the destroyed state . Or remove the fragment from the activity by calling the remove() and replace() methods of FragmentTransaction, but the addToBackStack() method is not called before the transaction is committed, and the fragment will also enter the destruction state at this time.

There are almost all the callback methods in the activity, but the fragments also provide some additional callback methods, so let's focus on these callbacks:

  • onAttach(). Invoked when a fragment is associated with an activity.
  • onCreateView(). Called when a view is created (layout loaded) for a fragment.
  • onActivityCreated(). Called when ensuring that the activity associated with the fragment must have been created.
  • onDestroyView(). Called when the view associated with the fragment is removed.

3.2 The process of life cycle

Please add a picture description

3.3 Life cycle process under common operations

When Activity loads Fragment , call the following methods in turn: onAttach -> onCreate -> onCreateView -> onActivityCreated -> onStart ->onResume

②When we create a suspended dialog-style Activity , or others, it is to make the Activity where the Fragment is located visible, but not to get the focus onPause

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

④ When we replace Fragment and call addToBackStack() to add it to the Back stack onPause -> onStop -> onDestoryView! !Note that the Fragment has not been destroyed at this time!!!

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

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

Content reference: "The First Line of Code" - Guo Lin

Guess you like

Origin blog.csdn.net/The_onion/article/details/126111485