Android---Activity和Fragment通信(一)

1、使用原生的方案,通过Bundle进行通信

//在Activity中定义一个按钮,通过Bundle传递信息给Fragment
private Button mReChange;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        mReChange = findViewById(R.id.fragment_rechange);
        mReChange.setOnClickListener(view -> {
            //传递数据,使用Bundle
            Bundle bundle = new Bundle();
            bundle.putString("message","需要磨练,学习编码");
            BlankFragment1 blankFragment1 = new BlankFragment1();
            blankFragment1.setArguments(bundle);
            replaceFragment(blankFragment1);
        });
    }
    //将Fragment添加到Activity
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_dynamic,fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
//todo 在BlankFragment1 中将获取到的信息显示出来
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //使用解析器去解析layout布局,并对其做判空处理,防止重复解析
        if (mInflate == null){
            mInflate = inflater.inflate(R.layout.fragment_blank1, container, false);
        }
        //获取传递过来的Bundle
        Bundle arguments = getArguments();
        mTextView = mInflate.findViewById(R.id.fragment_text);
        mButton = mInflate.findViewById(R.id.fragment_btn);
        mButton.setOnClickListener(view ->{
            if (arguments == null){
                mTextView.setText("好好学习");
            }else {
                mTextView.setText(arguments.getString("message"));
            }
        });
        return mInflate;
    }

效果如下:
在这里插入图片描述

2、使用java语言中类与类通信常用方案:接口

  • 定义一个接口
package com.example.viewexample.fragment;

public interface IFragmentCallback {
    //从Fragment发送信息给Activity
    void sendMsgToActivity(String msg);
    //从Activity中获取信息
    String getMsgFromActivity();
}

  • 定义一个Fragment
<!--xml布局文件-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".fragment.CommunicationFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:id="@+id/communication_message"
        android:textSize="20dp"
        android:text="@string/hello_blank_fragment" />

    <Button
        android:id="@+id/getMsgFromActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="从Activity获取信息" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sendMsgToActivity"
        android:text="给Activity发送信息"/>

</LinearLayout>
package com.example.viewexample.fragment;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.viewexample.R;

public class CommunicationFragment extends Fragment {

    private View mInflate;
    private Button mSendMsgToActivity;
    private Button mGetMsgFromActivity;
    private IFragmentCallback mIFragmentCallback;
    private TextView mMessage;
    private String mMsgFromActivity;
	//创建一个方法,将IFragmentCallback与Fragment关联起来
    public void setIFragmentCallback(IFragmentCallback callback){
        mIFragmentCallback = callback;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (inflater != null) {
            mInflate = inflater.inflate(R.layout.fragment_communication, container, false);
        }
        mMessage = mInflate.findViewById(R.id.communication_message);
        
        //给Activity发送消息
        mSendMsgToActivity = mInflate.findViewById(R.id.sendMsgToActivity);
        mSendMsgToActivity.setOnClickListener(View ->{
            mIFragmentCallback.sendMsgToActivity("Fragment从这里给Activity发送了消息");
        });
        
        //接收Activity中发送过来的消息
        mGetMsgFromActivity = mInflate.findViewById(R.id.getMsgFromActivity);
        mGetMsgFromActivity.setOnClickListener(View ->{
            mMsgFromActivity = mIFragmentCallback.getMsgFromActivity();
            mMessage.setText(mMsgFromActivity);
        });
        return mInflate;
    }
}
  • 对Activity进行操作
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        mChange = findViewById(R.id.fragment_change);
        mChange.setOnClickListener(view -> {
        	//1、创建fragment对象
            CommunicationFragment communicationFragment = new CommunicationFragment();
            //2、调用setIFragmentCallback并传递IFragmentCallback对象
            communicationFragment.setIFragmentCallback(new IFragmentCallback() {
                @Override
                public void sendMsgToActivity(String msg) {
                //注意:没有Fragment没有上下文,需要使用Fragment.this.getContext();
                    Toast.makeText(FragmentActivity.this,msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public String getMsgFromActivity() {
                    String msg = "成功从Activity中传递了信息给Fragment";
                    return msg;
                }
            });
            replaceFragment(communicationFragment);

        });
    }
    
    //将Fragment添加到Activity
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_dynamic,fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

效果如下:
从Activity获取信息
Fragment发送信息给Activity

3、学习中的笔记(提醒自己需要查阅已经封装好的架构方案)

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万卷书情似故人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值