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:
>
- Introduced in version 3.0, meaning minSdk must be greater than 11.
- Fragment must be nested within an Activity, and although it has its own lifecycle, it is influenced by the lifecycle of its host Activity. It is not recommended to nest Fragments within Fragments as their lifecycle becomes uncontrollable!
- The official documentation states that at least three methods need to be implemented when creating a Fragment: onCreate(), onCreateView(), and onPause(); however, it seems that only implementing onCreateView() is also acceptable.
- The lifecycle of a Fragment is somewhat similar to that of an Activity: it has three states.
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.
>
- Dialog: DialogFragment
- List: ListFragment
- Preferences: PreferenceFragment
- WebView Interface: WebViewFragment
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:
>
- If you use the Fragment from the v4 package, the Activity containing it must inherit from FragmentActivity.
- Previously, I wrote the following code and encountered an error: getFragmentManager() should be changed to getSupportFragmentManager().
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:
- Define an interface in the Fragment, with an abstract method that takes the data type you want to pass as a parameter.
- Implement the interface method in the Fragment to pass the data.
- In the Activity, call the method provided by the Fragment and override the abstract method to retrieve the data.
③ 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:
When an Activity loads a Fragment, the following methods are called in order:
onAttach
->onCreate
->onCreateView
->onActivityCreated
->onStart
->onResume
.When a dialog-style Activity or similar makes the Fragment's Activity visible but not focused:
onPause
.When the dialog closes and the Activity regains focus:
onResume
.When replacing a Fragment and adding it to the back stack with
addToBackStack()
:onPause
->onStop
->onDestroyView
. Note that the Fragment is not yet destroyed.When pressing the back button and the Fragment is displayed again:
onCreateView
->onActivityCreated
->onStart
->onResume
.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!
- 1.0 Android Basic Tutorial
- 1.0.1 2015 Latest Android Basic Tutorial Contents
- 1.1 Background and System Architecture Analysis
- 1.2 Development Environment Setup
- 1.2.1 Developing Android Apps with Eclipse + ADT + SDK
- 1.2.2 Developing Android Apps with Android Studio
- 1.3 Solving SDK Update Issues
- 1.4 Genymotion Emulator Installation
- 1.5.1 Git Tutorial: Basic Operations on Local Repository
- 1.5.2 Git: Setting Up a Remote Repository on GitHub
- 1.6 How to Use 9-Patch Images
- 1.7 Interface Prototype Design
- 1.8 Project Source Analysis (Files and Resource Access)
- 1.9 Signing and Packaging Android Applications
- 1.11 Decompiling APK to Retrieve Code and Resources
- 2.1 Concepts of View and ViewGroup
- 2.2.1 LinearLayout (Linear Layout)
- 2.2.2 RelativeLayout (Relative Layout)
- 2.2.3 TableLayout (Table Layout)
- 2.2.4 FrameLayout (Frame Layout)
- 2.2.5 GridLayout (Grid Layout)
- 2.2.6 AbsoluteLayout (Absolute Layout)
- 2.3.1 Detailed Explanation of TextView (Text View)
- 2.3.2 Detailed Explanation of EditText (Input Field)
- 2.3.3 Button and ImageButton
- 2.3.4 ImageView (Image View)
- 2.3.5. RadioButton (Radio Button) & Checkbox (Checkbox)
- 2.3.6 ToggleButton and Switch
- 2.3.7 ProgressBar (Progress Bar)
- 2.3.8 SeekBar (Drag Bar)
- 2.3.9 RatingBar (Star Rating Bar)
- 2.4.1 ScrollView (Scroll Bar)
- 2.4.2 Date & Time Components (Part 1)
- 2.4.3 Date & Time Components (Part 2)
- 2.4.4 Basic Adapter Explanation
- 2.4.5 Simple Usage of ListView
- 2.4.6 Optimization of BaseAdapter
- 2.4.7 Focus Issues with ListView
- 2.4.8 Solving Checkbox Misalignment in ListView
- 2.4.9 Data Update Issues with ListView
- 2.5.0 Building a Reusable Custom BaseAdapter
- 2.5.1 Implementing Multiple Item Layouts in ListView
- 2.5.2 Basic Usage of GridView (Grid View)
- 2.5.3 Basic Usage of Spinner (List Option Box)
- 2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Field)
- 2.5.5 Basic Usage of ExpandableListView (Collapsible List)
- 2.5.6 Basic Usage of ViewFlipper (Flip View)
- 2.5.7 Basic Usage of Toast
- 2.5.8 Detailed Explanation of Notification (Status Bar Notification)
- 2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
- 2.6.0 Basic Usage of Other Common Dialogs
- 2.6.1 Basic Usage of PopupWindow (Floating Box)
- 2.6.2 Menu (Menu)
- 2.6.3 Simple Usage of ViewPager
3.6 Responding to System Setting Events (Configuration Class)
5.1 Overview of Fragment
5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Sliding
5.2.5 Fragment Example - Simple Implementation of News (Shopping) App List Fragment
6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
6.3.1 Data Storage and Access - Introduction to SQLite Database
7.1.1 Android Network Programming and Learning HTTP Protocol
8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Frame Animation in Android Animation Collection
- 8.4.2 Tween Animation in Android Animation Collection
- 8.4.3 Property Animation in Android Animation Collection - Introduction
- 8.4.4 Property Animation in Android Animation Collection - Further Exploration
- 9.1 Playing Sound Effects with SoundPool (Duang~)
- 9.2 Audio and Video Playback with MediaPlayer
- 9.3 Taking Photos with Camera
- 9.4 Recording Audio with MediaRecord
- 10.1 TelephonyManager (Phone Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Series (1) - Introduction
- 10.11 Sensor Series (2) - Orientation Sensor
- 10.12 Sensor Series (3) - Accelerometer/Gyroscope Sensor
- 10.12 Sensor Series (4) - Understanding Other Sensors
- 10.14 Introduction to Android GPS
- 11.0 Completion of the 2015 Latest Android Basic Beginner's Tutorial
- 12.1 Android Practice: DrySister App (Version 1) - Project Setup and Basic Implementation
- 12.2 DrySister App (Version 1) - Parsing Backend Data
- 12.3 DrySister App (Version 1) - Image Loading Optimization (Building a Simple Image Cache Framework)
- 12.4 DrySister App (Version 1) - Adding Data Caching (Introducing SQLite)
- 12.5 DrySister App (Version 1) - Code Review, Adjustments, and Logging Class Writing
- 12.6 DrySister App (Version 1) - Icon Creation, Obfuscation, Signing and Packaging, APK Slimming, App Release