android:fragment给activity发送消息
一,代码
activity xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.Message2Activity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textReceive"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="接收到的消息"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="我是Activity" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="500dp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
activity java
package com.example.okdemo1.activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.okdemo1.R;
import com.example.okdemo1.fragment.Msg2Fragment;
import com.example.okdemo1.fragment.MsgFragment;
import com.example.okdemo1.interfaces.FragmentCommunicator;
public class Message2Activity extends AppCompatActivity implements FragmentCommunicator {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_message2);
// 步骤1:获取FragmentManager
// FragmentManager fragmentManager = getFragmentManager();
FragmentManager fragmentManager = getSupportFragmentManager();
// 步骤2:获取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// 步骤3:创建需要添加的Fragment
final Msg2Fragment fragment = new Msg2Fragment();
// 步骤4:动态添加fragment
// 即将创建的fragment添加到Activity布局文件中定义的占位符中(FrameLayout)
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commitNow();
}
@Override
public void onMessageReceived(String message) {
TextView text2 = findViewById(R.id.text);
text2.setText("接收到消息:"+message);
// 处理消息
Toast.makeText(this, "接收到消息:"+message, Toast.LENGTH_LONG).show();
}
}
fragment 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=".fragment.Msg2Fragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
>
<TextView
android:id="@+id/fragment"
android:text="我是fragment"
android:layout_gravity="center"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="点击发送消息"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
fragment java
package com.example.okdemo1.fragment;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.okdemo1.R;
import com.example.okdemo1.interfaces.FragmentCommunicator;
/**
* A simple {@link Fragment} subclass.
* Use the {@link Msg2Fragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class Msg2Fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private FragmentCommunicator mListener;
public Msg2Fragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (FragmentCommunicator) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement FragmentCommunicator");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Msg2Fragment.
*/
// TODO: Rename and change types and number of parameters
public static Msg2Fragment newInstance(String param1, String param2) {
Msg2Fragment fragment = new Msg2Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_msg2, container, false);
//给按钮增加点击事件
Button button2 = contentView.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送消息
String message = "夜凉疑有雨,院静似无僧";
sendMessageToActivity(message);
}
});
return contentView;
}
//发送消息
public void sendMessageToActivity(String message) {
if (mListener != null) {
mListener.onMessageReceived(message);
}
}
}
interface
package com.example.okdemo1.interfaces;
public interface FragmentCommunicator {
void onMessageReceived(String message);
}
二,测试效果:

浙公网安备 33010602011771号