Easy Tutorial
❮ Php Delete An Element From An Array The Different Of Jre And Jdk ❯

5.1 Overview of Fragment Basics

Classification Android Basic Tutorial

Introduction to This Section

>

In the previous chapter, we covered the four major components of Android: Activity, Service, BroadcastReceiver, and ContentProvider, as well as their link: Intent. In this chapter, we introduce the concept of a Fragment, which is a small piece of activity. This section will explain the basic concepts and usage of Fragment. Official Documentation: 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. It was originally designed to accommodate large-screen tablet devices. Now, it remains a favorite for tablet app UI design, and it is also commonly used in regular phone app development. We can think of it as a mini-Activity, also known as an Activity fragment! Imagine if you had a large interface with only one layout; designing the interface would be very cumbersome, and managing multiple components would be even more challenging. Using Fragment, we can divide the screen into several parts and manage them in groups, enabling more modular management! This allows for easier dynamic updates to the user interface of the Activity during runtime. Additionally, Fragment cannot be used alone; it must be nested within an Activity. Although it has its own lifecycle, it is still influenced by the lifecycle of its host Activity, such as being destroyed along with the Activity.

The following diagram from the documentation shows how a Fragment handles different scenarios between phones and tablets:

PS: A simple news browsing page, using two Fragments to display the news list and news content respectively.


2) Fragment Lifecycle Diagram


3) Key Points:

Here are some key points about using Fragment:

>


4) Subclasses of Fragment:

PS: Often, we directly override Fragment, inflate the layout, and complete the corresponding business logic. Subclasses are not used much, and can be studied further when needed.

>


5) Using Fragment from the App package or the v4 package:

Problem Overview:

Many people encounter the following situation when using Fragment:

So, should we use the Fragment from the android.app package or the android.support.v4.app package?

>

Answer: Both can be used. As mentioned earlier, Fragment was introduced in Android 3.0 (API 11). So, what if the app needs to run on versions below 3.0, such as the still somewhat popular 2.3? That's where the v4 package comes in, which can be compatible down to version 1.6. The choice depends on your needs. Now, the market share of phones below 3.0 is already minimal, with most being above 4.0, and 6.0 was released in October. So, you can directly use the Fragment from the app package and call the relevant methods, which usually won't cause any issues. If you use the Fragment from the app package, both FragmentManager and FragmentTransaction must also be from the app package. Either use all from the app package or all from the v4 package, otherwise, errors may occur. If you want your app to be compatible with older versions of phones, you can choose the v4 package.

Points to Note When Using the v4 Package Fragment:

>


2. Creating a Fragment

1) Static Loading of Fragment

Implementation Process:

Sample Code:

Step 1: Define the layout for the Fragment, which is the content displayed by the fragment. Step 2: Create a custom Fragment class, which must inherit from Fragment or one of its subclasses, and override the onCreateView() method. In this method, call the inflater.inflate() method to load the Fragment's layout file, 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 to the layout file of the Activity where the Fragment needs to be loaded. Remember, the name attribute should be the fully qualified class name, including 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: In the Activity's onCreate() method, call setContentView() to load the layout file.


2) Dynamic Loading of Fragment

Implementation Process:

Sample Code: This demonstrates switching Fragments when the screen orientation changes:

Fragment and layout code is omitted, focusing on the key code in 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();
        }
        else
        {
            Fragment2 f2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f2).commit();
        }
    }   
}

3. Fragment Management and Fragment Transactions


4. Interaction Between Fragment and Activity

Some may prefer text over diagrams, so here's a textual explanation:

1) Component Access

Fragment accessing components in Activity: getActivity().findViewById(R.id.list);getFragmentManager.findFragmentById(R.id.fragment1);**


2) Data Transfer

①Activity passing data to Fragment:

In the Activity, create a Bundle data package, call the setArguments(bundle) method of the Fragment instance, thus passing the Bundle data package to the Fragment. Then, in the Fragment, call getArguments to obtain the Bundle object and parse it.

②Fragment passing data to Activity:

Define an internal callback interface in the Fragment, and have the Activity containing the Fragment implement this callback interface. The Fragment can then pass data through the callback interface. Callback interfaces are well-known concepts, but many people struggle to implement them. Here's a partial code example, which should be straightforward:

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

/* Interface */  
public interface CallBack{  
    /* Method to get information */  
    public void getResult(String result);  
}

Step 2: Interface callback (in Fragment):

/* Interface callback */  
public void getData(CallBack callBack){  
    /* Get the information from the text box, or other parameters as needed */  
    String msg = editText.getText().toString();  
    callBack.getResult(msg);  
}

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

/* Using the interface callback method to get data */  
leftFragment.getData(new CallBack() {  
    @Override  
    public void getResult(String result) {  
        /* Display the message */  
        Toast.makeText(MainActivity.this, "-->>" + result, Toast.LENGTH_SHORT).show();  
    }  
});

Summary of the Method:

③ Data Transfer Between Fragments:

This is straightforward. Find the fragment object that will receive the data and call setArguments to pass the data. Typically, this is done during a fragment transition (replace operation) by initializing the target Fragment and calling its setArguments method with the data.

Example Code:

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. Walking Through the Lifecycle Diagram:

To deepen your understanding of the Fragment lifecycle, let's walk through it briefly:

  1. When an Activity loads a Fragment, the following methods are called in order: onAttach -> onCreate -> onCreateView -> onActivityCreated -> onStart -> onResume.

  2. When a dialog-style Activity or similar makes the Fragment's Activity visible but not focused: onPause.

  3. When the dialog closes and the Activity regains focus: onResume.

  4. When replacing a Fragment and adding it to the back stack with addToBackStack(): onPause -> onStop -> onDestroyView. Note that the Fragment is not yet destroyed.

  5. When pressing the back button and the Fragment is displayed again: onCreateView -> onActivityCreated -> onStart -> onResume.

  6. If the Fragment is not added to the back stack with addToBackStack() before committing the transaction, or if the Activity is exited, the Fragment will be completely destroyed: onPause -> onStop -> onDestroyView -> onDestroy -> onDetach.


Summary:

This section covered the basic concepts and usage of Fragments. You will gradually appreciate Fragments due to their flexibility. Due to space constraints, this concludes the basic introduction. The next section will cover common Fragment examples. Stay tuned!

Follow on WeChat

❮ Php Delete An Element From An Array The Different Of Jre And Jdk ❯