Hướng dẫn phát triển ứng dụng Android: Fragments động trong phần 2

Khám phá phát triển ứng dụng Android với hướng dẫn thân thiện cho não bộ trong phần 2 của sách Head First Android Development, ấn bản thứ 2.

Trường đại học

Trường Đại Học

Chuyên ngành

Phát Triển Ứng Dụng Android

Người đăng

Ẩn danh

Thể loại

hướng dẫn

2025

456
3
0

Phí lưu trữ

75 Point

Mục lục chi tiết

11. CHƯƠNG 11: DYNAMIC FRAGMENTS

11.1. Nesting Fragments

11.2. Adding dynamic fragments

11.3. App structure

11.4. Convert stopwatch

11.5. Test stopwatch

11.6. Add to fragment

11.7. StopwatchFragment code

11.8. StopwatchFragment.java (continued)

11.9. The StopwatchFragment layout

11.10. layout, continued

Tóm tắt

I. Tổng quan về Fragments trong Android Hướng dẫn chi tiết

Fragments là một phần quan trọng trong phát triển ứng dụng Android, cho phép chia nhỏ giao diện người dùng thành các phần độc lập. Việc sử dụng Fragments trong Android giúp tăng tính linh hoạt và khả năng tái sử dụng mã nguồn. Bài viết này sẽ cung cấp cái nhìn tổng quan về cách sử dụng Fragments, từ việc tạo đến quản lý chúng trong ứng dụng.

1.1. Fragments là gì Khái niệm và ứng dụng

Fragments là một phần của giao diện người dùng trong ứng dụng Android, có thể được tái sử dụng và quản lý độc lập. Chúng cho phép phát triển giao diện người dùng phức tạp hơn mà không cần phải tạo nhiều Activity.

1.2. Lợi ích của việc sử dụng Fragments trong phát triển ứng dụng

Sử dụng Fragments giúp giảm thiểu mã nguồn, tăng tính linh hoạt và khả năng bảo trì. Chúng cũng cho phép tạo ra các giao diện người dùng tương thích với nhiều kích thước màn hình khác nhau.

II. Vấn đề thường gặp khi sử dụng Fragments trong Android

Mặc dù Fragments mang lại nhiều lợi ích, nhưng cũng có một số thách thức khi sử dụng chúng. Các vấn đề như quản lý vòng đời của Fragments và tương tác giữa Activity và Fragments có thể gây khó khăn cho lập trình viên.

2.1. Quản lý vòng đời của Fragments Thách thức và giải pháp

Vòng đời của Fragments phức tạp hơn so với Activity. Việc hiểu rõ các phương thức như onCreate, onStart, onResume là rất quan trọng để đảm bảo Fragments hoạt động đúng cách.

2.2. Tương tác giữa Activity và Fragments Cách giải quyết

Tương tác giữa Activity và Fragments có thể gây ra lỗi nếu không được quản lý đúng cách. Sử dụng FragmentTransaction trong Android giúp đảm bảo rằng các Fragments được thêm, thay thế hoặc xóa một cách an toàn.

III. Phương pháp tạo Fragments động trong ứng dụng Android

Tạo Fragments động cho phép cập nhật nội dung của Fragments mà không cần phải thay đổi Activity. Điều này rất hữu ích trong các ứng dụng yêu cầu cập nhật dữ liệu thường xuyên.

3.1. Cách tạo Fragments động Hướng dẫn từng bước

Để tạo Fragments động, cần sử dụng FragmentTransaction để thêm hoặc thay thế Fragments trong Activity. Việc này giúp cập nhật giao diện người dùng mà không cần khởi động lại Activity.

3.2. Sử dụng ViewModel với Fragments Tăng cường hiệu suất

Kết hợp ViewModel với Fragments giúp quản lý dữ liệu hiệu quả hơn. ViewModel giữ dữ liệu sống sót qua các thay đổi vòng đời, giúp Fragments không bị mất dữ liệu khi bị tái tạo.

IV. Ứng dụng thực tiễn của Fragments trong phát triển ứng dụng Android

Fragments được sử dụng rộng rãi trong các ứng dụng Android hiện đại. Chúng cho phép phát triển giao diện người dùng phức tạp và tương tác tốt hơn với người dùng.

4.1. Ví dụ thực tế về ứng dụng sử dụng Fragments

Nhiều ứng dụng như Facebook và Instagram sử dụng Fragments để quản lý các tab và giao diện người dùng phức tạp. Việc này giúp người dùng dễ dàng điều hướng giữa các phần khác nhau của ứng dụng.

4.2. Kết quả nghiên cứu về hiệu suất của Fragments

Nghiên cứu cho thấy rằng việc sử dụng Fragments có thể cải thiện hiệu suất của ứng dụng, giảm thiểu thời gian tải và tăng trải nghiệm người dùng.

V. Kết luận Tương lai của Fragments trong phát triển ứng dụng Android

Fragments sẽ tiếp tục đóng vai trò quan trọng trong phát triển ứng dụng Android. Với sự phát triển của công nghệ, việc sử dụng Fragments sẽ ngày càng trở nên phổ biến và cần thiết.

5.1. Xu hướng mới trong việc sử dụng Fragments

Các xu hướng mới như Navigation Component sẽ giúp đơn giản hóa việc quản lý Fragments, làm cho việc phát triển ứng dụng trở nên dễ dàng hơn.

5.2. Tương lai của Fragments trong các ứng dụng di động

Với sự phát triển không ngừng của Android, Fragments sẽ tiếp tục được cải tiến và tối ưu hóa, mang lại nhiều lợi ích cho lập trình viên và người dùng.

17/07/2025
Head first android development a brain friendly guide 2nd edition part 2

Trích đoạn nội dung tài liệu

11 dynamic fragments Nesting Fragments The Back button was going crazy, transactions everywhere. So I hit them with the getChildFragmentManager() method and BAM! Everything went back to normal. So far you’ve seen how to create and use static fragments. But what if you want your fragments to be more dynamic? Dynamic fragments have a lot in common with dynamic activities, but there are crucial differences you need to be able to deal with. In this chapter you’ll see how to convert dynamic activities into working dynamic fragments.

You’ll find out how to use fragment transactions to help maintain your fragment state. Finally, you’ll discover how to nest one fragment inside another, and how the child fragment manager helps you control unruly back stack behavior. this is a new chapter   433 dynamic fragments Adding dynamic fragments In Chapters 9 and 10, you saw how to create fragments, how to include them in activities, and how to connect them together. To do this, we created a list fragment displaying a list of workouts, and a fragment displaying details of a single workout.

These fragments we’ve created so far have both been static. Once the fragments are displayed, their contents don’t change. We may completely replace the fragment that’s displayed with a new instance, but we can’t update the contents of the fragment itself. In this chapter we’re going to look at how you deal with a fragment that’s more dynamic.

By this, we mean a fragment whose views gets updated after the fragment is displayed. To learn how to do, we’re going to change the stopwatch activity we created in Chapter 4 into a stopwatch We’re only showing the tablet fragment. We’re going to add our new stopwatch fragment to version of the app here, but the WorkoutDetailFragment so that it’s displayed underneath new stopwatch fragment will the details of the workout. appear in the phone version too.

WorkoutDetailFragment displays details of the workout the user clicks on. We’re going to add a stopwatch fragment to WorkoutDetailFragment. WorkoutListFragment contains a list of workouts. These lines won’t appear in the actual app.

We’ve added them here to show you each of the fragments. 434  Chapter 11 dynamic fragments Here’s what we’re going to do There are a number of steps we’ll go through to change the app to display the stopwatch: 1 Convert StopwatchActivity into StopwatchFragment. We’ll take the StopwatchActivity code we created in Chapter 4, and change it into fragment code. We’ll also display it in a new temporary activity called TempActivity so that we can check that it works.

We’ll temporarily change the app so that TempActivity starts when the app gets launched. The StopwatchActivity included Start, Stop, and Reset buttons.We need to check that these still work when the stopwatch code is in a fragment. We also need to test what happens to StopwatchFragment when the user rotates the device. We’ll start by adding 3 Add StopwatchFragment to WorkoutDetailFragment.

StopwatchFragment Once we’re satisfied that StopwatchFragment works, we’ll to a new activity add it to WorkoutDetailFragment. When we’re satisfied that StopwatchFragment works OK in TempActivity, we’ll add it to WorkoutDetailFragment. Do this! Let’s get started. We’re going to update the Workout app in this chapter, so open your original Workout project from Chapter 9 in Android Studio.

you are here 4  435 app structure Convert stopwatch Test stopwatch The new version of the app Add to fragment We’re going to change our app to get StopwatchFragment working in a new temporary activity called TempActivity. This will emable us to confirm that StopwatchFragment works before we add it to WorkoutDetailFragment later in the chapter. Here’s how the new version of the app will work: 1 When the app gets launched, it starts TempActivity. TempActivity uses activity_temp.xml for its layout, and contains a fragment, StopwatchFragment.

2 StopwatchFragment displays a stopwatch with Start, Stop, and Reset buttons. <Layout> <Layout> </Layout> </Layout> activity_temp.xml fragment_ stopwatch.java Stopwatch Device Fragment.java All of the other activities and fragments we created in Chapters 9 and 10 will still exist in the project, but we’re not going to do anything with them until later in the chapter. 436  Chapter 11 dynamic fragments Convert stopwatch Test stopwatch Create TempActivity Add to fragment We’ll start by creating TempActivity. Create a new empty activity by switching to the Project view of Android Studio’s explorer, highlighting the com.workout package in the app/src/main/java folder, going to the File menu and choosing New.→Activity→Empty Activity.

Name the activity “TempActivity”, name the layout “activity_temp”, make sure If prompted for the the package name is com.workout, and check the activity’s source language, Backwards Compatibility (AppCompat) checkbox. select the option for Java. We’re going to change our app so that, when it’s launched, it starts TempActivity instead of MainActivity. To do this, we need to move MainActivity’s launcher intent filter to TempActivity instead.

Open the file AndroidManifest.xml in the app/src/main folder, then make the following changes: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.com/apk/res/android" package="com.workout"> Workout <application. app/src/main <xml> <activity android:name=".MainActivity"> </xml> <intent-filter> AndroidManifest.xml <action android:name="android.MAIN" /> <category android:name="android.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DetailActivity" /> This bit specifies <activity android:name=".TempActivity"> that it’s the main <intent-filter> activity of the app. <action android:name="android.MAIN" /> <category android:name="android.LAUNCHER" /> </intent-filter> </activity> This says the activity can </application> be used to launch the app. </manifest> We’ll update TempActivity on the next page.

you are here 4  437 TempActivity code Convert stopwatch Test stopwatch TempActivity needs to extend Add to fragment AppCompatActivity All of the fragments we’re using in this app come from the Support Library. As we said back in Chapter 9, all activities that use Support Library fragments must extend the FragmentActivity class or one of its subclasses such as AppCompatActivity. If they don’t, the code will break. All of the other activities we’ve created in this app extend AppCompatActivity, so we’ll make TempActivity extend this class too.

Here’s our code for TempActivity. Update your version of the code so that it matches ours below: package com.workout; Workout import android.AppCompatActivity; import android.Bundle; The activity extends AppCompatActivity. app/src/main public class TempActivity extends AppCompatActivity { java com.workout @Override protected void onCreate(Bundle savedInstanceState) { TempActivity.activity_temp); } } We’ll add a new stopwatch fragment We’re going to add a new stopwatch fragment called StopwatchFragment.java that uses a layout called fragment_stopwatch. We’re going to base the fragment on the stopwatch activity we created back in Chapter 4.

We already know that activities and fragments behave in similar ways, but we also know that a fragment is a distinct type of object—a fragment is not a subclass of activity. Is there some way we could rewrite that stopwatch activity code so that it works like a fragment? 438  Chapter 11 dynamic fragments Fragments and activities have similar lifecycles. To understand how to rewrite an activity as a fragment, we need to think a little about the similarities and differences between them. If we look at the lifecycles of fragments and activities, we’ll see that they’re very similar: Lifecycle method Activity Fragment onAttach() onCreate() onCreateView() onActivityCreated() onStart() onPause() onResume() onStop() onDestroyView() onRestart() onDestroy() onDetach() .but the methods are slightly different Fragment lifecycle methods are almost the same as activity lifecycle methods, but there’s one major difference: activity lifecycle methods are protected and fragment lifecycle methods are public.

And we’ve already seen that the ways that activities and fragments create a layout from a layout resource file are different. Also, in a fragment, we can’t call methods like findViewById() directly. Instead, we need to find a reference to a View object, and then call the view’s findViewById() method. With these similarities and differences in mind, it’s time you started to write some code.

you are here 4  439 exercise This is the code for StopwatchActivity we wrote earlier. You’re going to convert this code into a fragment called StopwatchFragment. With a pencil, make the changes you need. Keep the following things in mind: - Instead of a layout file called activity_stopwatch.xml, it will use a layout called fragment_stopwatch.

- Make sure the access restrictions on the methods are correct. - How will you specify the layout? - The runTimer() method won’t be able to call findViewById(), so you might want to pass a View object into runTimer(). public class StopwatchActivity extends Activity { //Number of seconds displayed on the stopwatch. private int seconds = 0; The number of seconds that have passed //Is the stopwatch running? private boolean running; running says whether the stopwatch is running.

private boolean wasRunning; wasRunning says whether the stopwatch was running before the stopwatch was paused. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); If the activity was destroyed and recreated, restore the state of the variables from setContentView(R.activity_stopwatch); if (savedInstanceState != null) { the savedInstanceState Bundle.getInt("seconds"); running = savedInstanceState.getBoolean("running"); wasRunning = savedInstanceState. } @Override protected void onPause() { Stop the stopwatch if the activity is paused.onPause(); wasRunning = running; running = false; } 440  Chapter 11 dynamic fragments @Override protected void onResume() { Start the stopwatch if the activity is resumed.onResume(); if (wasRunning) { running = true; } } Save the activity’s state before the activity is destroyed. @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean("wasRunning", wasRunning); } public void onClickStart(View view) { running = true; } public void onClickStop(View view) { Start, stop, or reset the stopwatch running = false; depending on which button is clicked.

} public void onClickReset(View view) { running = false; seconds = 0; Use a Handler to post code to } incremen t the number of seconds and update the text view every second. private void runTimer() { final TextView timeView = (TextView)findViewById(R.time_view); final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { int hours = seconds/3600; int minutes = (seconds%3600)/60; int secs = seconds%60; String time = String.setText(time); if (running) { seconds++; } handler.postDelayed(this, 1000); } }); } } you are here 4  441 solution fragment This is the code for StopwatchActivity we wrote earlier. You’re going to convert this code into a fragment called StopwatchFragment. With a pencil, make the changes you need.

Keep the following things in mind: - Instead of a layout file called activity_stopwatch.xml, it will use a layout called fragment_stopwatch. - Make sure the access restrictions on the methods are correct. - How will you specify the layout? - The runTimer() method won’t be able to call findViewById(), so This is the new name. you might want to pass a View object into runTimer().

public class StopwatchActivity StopwatchFragment extends Activity { Fragment //Number of seconds displayed on the stopwatch. private int seconds = 0; We’re extending //Is the stopwatch running? Fragment, not Activity. private boolean running; private boolean wasRunning; @Override This method needs to be public. protected public void onCreate(Bundle savedInstanceState) { You don’t set a fragment’s layout super.activity_stopwatch); if (savedInstanceState != null) { in its onCreate() method.getInt("seconds"); running = savedInstanceState.getBoolean("running"); wasRunning = savedInstanceState.getBoolean("wasRunning"); } runTimer(); We’re not calling runTimer() yet because we’ve We can leave this code in the } not set the layout—we don’t have any views yet.

@Override We set the fragment’s layout in public View onCreateView(LayoutInflater inflater, ViewGroup container, the onCreateView() method. Bundle savedInstanceState) { View layout = inflater.fragment_stopwatch, container, false); runTimer(layout); Pass the layout view to the runTimer() method. return layout; } @Override This method needs to be public. protected public void onPause() { super.onPause(); wasRunning = running; running = false; } 442  Chapter 11 dynamic fragments @Override This method needs to be public.

protected public void onResume() { super.putBoolean("wasRunning", wasRunning); } public void onClickStart(View view) { running = true; } public void onClickStop(View view) { running = false; } public void onClickReset(View view) { running = false; seconds = 0; } The runTimer() method now takes a View. private void runTimer( View view ) { final TextView timeView = (TextView) view.time_view); final Handler handler = new Handler(); handler. @Override public void run() { int hours = seconds/3600; int minutes = (seconds%3600)/60; int secs = seconds%60; String time = String.setText(time); if (running) { seconds++; } handler.postDelayed(this, 1000); } }); } } you are here 4  443 StopwatchFragment code Convert stopwatch Test stopwatch The StopwatchFragment.

Nội dung được bảo vệ bản quyền — Tải xuống đầy đủ