Android:手把手教你 实现Activity 与 Fragment 相互通信 动态传值

本文详细介绍了在Android开发中,如何实现Activity向Fragment传递数据,包括通过接口回调的方式进行通信,以解决实际开发中的数据交互问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

  • ActivityFragment 的使用在Android开发中非常多
  • 今天,我将主要讲解 ActivityFragment 如何进行通信,实际上是要解决两个问题:
    1. Activity 如何传递数据到 Fragment
    2. Fragment如何传递数据到Activity

  问题1: Activity 如何传递数据到 Fragment?

       采用 Bundle 方式      activity传值fragment

       采用接口回调方式      fragment传值给activity

activity_main.xml 布局

<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="com.bwie.ceshi.MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="点我给fragment传递值"
        android:textSize="20dp" />

    <FrameLayout
        android:layout_marginTop="100dp"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:layout_below="@+id/button" />


</LinearLayout>
    fragment.xml 布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="我是fragment"
        android:textSize="30dp" />

    <EditText
        android:id="@+id/ed"
        android:hint="请输入要传递的值"
        android:ems="20"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="等待Activity发送消息"
        android:textSize="20dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:text="点击给Activity发消息"
        android:textSize="20dp" />


</LinearLayout>
步骤3:设置Activity的类文件
public class MainActivity extends AppCompatActivity {

    private TextView text;
    private com.bwie.ceshi.mFragment mFragment;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件
        text = findViewById(R.id.text);
        // 步骤1:获取FragmentManager
        FragmentManager fragmentManager =getSupportFragmentManager();
        // 步骤2:获取FragmentTransaction 开启事务
        final FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
        // 步骤3:创建需要添加的Fragment
        mFragment = new mFragment();
        // 步骤7:动态添加fragment
        beginTransaction.add(R.id.fragment_container, mFragment).commit();
        //点击事件进行传值---传到fragment
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 步骤4:创建Bundle对象
                // 作用:存储数据,并传递到Fragment中
                Bundle bundle=new Bundle();
                // 步骤5:往bundle中添加数据
                bundle.putString("chuan","我是你大哥");
                // 步骤6:把数据设置到Fragment中
                mFragment.setArguments(bundle);
                mFragment.setFragment();
            }
        });
        //获取fragment传递过来的值,通过接口
        mFragment.setActivity(new mFragment.ICallBack() {
            @Override
            public void get_message_from_Fragment(String string) {
                //给控件进行赋值
                text.setText(string);
            }
        });
    }
}
步骤4:设置Fragment的类文件
 
  
public class mFragment extends Fragment {

    private TextView fragment;
    private TextView text;
    private Button button;
    private EditText ed;
    ICallBack iCallBack;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        fragment = view.findViewById(R.id.fragment);
        ed = view.findViewById(R.id.ed);
        text = view.findViewById(R.id.text);
        button = view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = ed.getText().toString().trim();
                if(TextUtils.isEmpty(trim)){
                    Toast.makeText(getActivity(),"输入的值不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
               //通过接口对象,给activity发送值
             iCallBack.get_message_from_Fragment(trim);
            }
        });
        return view;
    }
    //更改fragment的值
    public void setFragment(){
        //获取activity传的值
        Bundle bundle = getArguments();
        if(bundle!=null){
            //获取传过来的值
            String chuan = bundle.getString("chuan");
            //设置值
            text.setText(chuan);
        }
    }
    //定义接口供外部访问
    interface ICallBack {
        void get_message_from_Fragment(String string);
    }
    //写一个方法供外部访问
    public void setActivity(ICallBack iCallBack){
        this.iCallBack=iCallBack;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值