Master the soul of Android Fragment development: in-depth analysis of Fragment (middle)


In the last article, we explored the core features, advantages, life cycle of Fragment, and how to use Fragment statically and dynamically. For interested friends, please go to: Master the soul of Android Fragment development: in-depth analysis of Fragment (I)


In this article, we will continue to explore Android Fragment in depth, including the following core topics:

Fragment communication

  • Fragment transfers data to activity
  • Activity transfers data to Fragment
  • Communication mode between fragments

Through comprehensive theoretical analysis, vivid example code and practical experience sharing, this article will help you thoroughly master the use skills of Fragment in Android application development, and improve code maintainability and user experience. Now, let's start this exciting Fragment journey together!


In Android applications, data communication is usually required between activities and fragments, and between fragments and fragments. For this cross level communication, we have a variety of options, and each method has its own application scenarios. Next, let's disassemble them one by one.


1、 Fragment transfers data to activity


When Fragment needs to transfer data to host activity, there are several common ways:


1. Callback through interface


This is the most common and standard practice. We need to define an interface in Fragment and implement its methods in Activity. When Fragment needs to transfer data, just call the method in the interface.

Implementation details are as follows:

 //Define Interface public interface DataTransferInterface { void onDataReceived(String data); } //Fragment Implementation public class MyFragment extends Fragment { private DataTransferInterface dataTransferInterface; @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof DataTransferInterface) { dataTransferInterface = (DataTransferInterface) context; } else { throw new RuntimeException("Activity must implement DataTransferInterface"); } } public void sendData(String data) { dataTransferInterface.onDataReceived(data); } } //Activity Implementation Interface public class MainActivity extends AppCompatActivity implements DataTransferInterface { @Override public void onDataReceived(String data) { //Processing data transferred from Fragment } }

2. Through ViewModel


If the application uses the ViewModel architecture component, it is also a good choice to share the ViewModel instance. Fragment can update the data in the ViewModel, and Activity listens to and responds to these data changes.


Step 1: Create the ViewModel class

 public class SharedViewModel extends ViewModel { private MutableLiveData<String> mMessage = new MutableLiveData<>(); public LiveData<String> getMessage() { return mMessage; } public void setMessage(String message) { mMessage.setValue(message); } }

stay SharedViewModel We defined a private mMessage MutableLiveData object and a public getMessage() Method to get LiveData. setMessage() Method is used to set mMessage The value of.


Step 2: Create Fragment layout and class

 fragment_share_data.xml
 <?xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android " android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter some text" /> <Button android:id="@+id/button_share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share Data" /> </LinearLayout> ShareDataFragment.java
 public class ShareDataFragment extends Fragment { private SharedViewModel viewModel; private EditText editText; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_share_data, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); editText = view.findViewById(R.id.edit_text); view.findViewById(R.id.button_share).setOnClickListener(v -> { viewModel.setMessage(editText.getText().toString()); }); } }

stay ShareDataFragment In, we first obtain SharedViewModel Instance of. Then, we onViewCreated() Method to set the button click event listener. When clicking the button, we will pass the text in EditText to the setMessage() method.


Step 3: Create Activity Layout and Class

 activity_main.xml
 <?xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android " android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" /> </LinearLayout>
 MainActivity.java
 public class MainActivity extends AppCompatActivity { private TextView textView; private SharedViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text_view); viewModel = new ViewModelProvider(this).get(SharedViewModel.class); viewModel.getMessage().observe(this, message -> { textView.setText(message); }); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new ShareDataFragment()) .commit(); } } }

stay MainActivity In, we first obtain SharedViewModel Instance of. Then, we observe the LiveData object in the ViewModel and update the text of the TextView when the data changes.


Finally, we onCreate() Method ShareDataFragment To the layout of the activity.

After running the sample application, you will see a fragment containing EditText and buttons. When you enter some text in EditText and click the "Share Data" button, the text will be passed to the ViewModel and displayed in the TextView of the Activity.


3. Through the Event Bus


Using event bus libraries (such as EventBus or RxBus) is also a solution. Fragment sends events, and Activity registers to listen and process events. This method is flexible, but it also adds complexity.


The following is a complete case of using the EventBus library to demonstrate data transfer from Fragment to Activity.


Step 1: Add EventBus dependency

First, we need to build.gradle Add the dependencies of the EventBus library to the file:

 dependencies { implementation 'org.greenrobot:eventbus:3.3.1' }

Step 2: Define the event class

We need to define an event class to transfer data between Fragment and Activity.

 public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } }

Step 3: Create Fragment layout and class

 fragment_share_data.xml
 <?xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android " android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter some text" /> <Button android:id="@+id/button_share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share Data" /> </LinearLayout>
 ShareDataFragment.java
 public class ShareDataFragment extends Fragment { private EditText editText; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_share_data, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editText = view.findViewById(R.id.edit_text); view.findViewById(R.id.button_share).setOnClickListener(v -> { String message = editText.getText().toString(); EventBus.getDefault().post(new Mess
comment
Add Red Packet

Please fill in the red envelope greeting or title

individual

The minimum number of red packets is 10

element

The minimum amount of red packet is 5 yuan

Current balance three point four three element Go to recharge>
To be paid: ten element
Achieve 100 million technicians!
After receiving, you will automatically become a fan of the blogger and the red envelope owner rule
hope_wisdom
Red packet sent

Reward the author

W rain or shine w

Your encouragement will be the greatest impetus for my creation

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
Scan code for payment: ¥1
Obtaining
Scan code for payment

Your balance is insufficient, please change the scanning code to pay or Recharge

Reward the author

Paid in element
Payment with balance
Click to retrieve
Scan code for payment
Wallet balance zero

Deduction description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted at a ratio of 1:1.
2. The balance cannot be directly purchased and downloaded, but VIP, paid columns and courses can be purchased.

Balance recharge