一。什么情况下需要Activity与Fragment之间进行通信。
Activity与Fragment之间进行通信的情况通常包括数据传递、状态变化通知、生命周期控制等多种情形,主要为了实现整个UI界面的协调和交互。
举例说明:当我们实现一个图文分享功能,当点击分享按钮时,会弹出ShareDialogFragment的弹窗页面,点击里面的分享至微信好友,那么ShareDialogFragment需要获取当前图文的内容,然后进行分享。所以Activity需要将图文内容传递给Fragment,这就是二者通信的重要性。
同样,Fragment往Activity中传递消息也是十分重要的。
二。Activity与Fragment进行通信有哪几种方式
1.使用Bundle
当利用Activity给Fragment传递消息时,首先我们需要在Activity中将要传递的信息传进Bundle中,在Activity实例化Fragment,从Fragent中获取Bundle对象。
例子:当点击按钮时,按钮下部的FrameLayout会显示从Activity中传递的内容。
(1)创建Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_bundle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="通过Bundle传递消息"/>
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
(2)创建MainActivity.class
package com.example.activitytofragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity{
private Button btnBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setListeners();
}
private void setListeners() {
btnBundle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessageToFragment();
}
});
}
private void findViews() {
btnBundle = findViewById(R.id.btn_bundle);
}
private void sendMessageToFragment() {
Bundle bundle = new Bundle();
bundle.putString("message","我是Activity传给Fragment的值");
BlankFragment fragment = (BlankFragment) getSupportFragmentManager().findFragmentById(R.id.fl_content);
if(fragment == null) {
fragment = new BlankFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_content,fragment).commit();
}
fragment.setArguments(bundle);
}
}
(3)创建fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
(4)创建BlankFragment.class
2.接口回调
3.广播
4.ViewModel
5.EventBus
6.通过Handler
先到这里,后续的方法在之后的文章里会介绍。