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

Android---Activity和Fragment通信(一),第1张

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


<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();
    }

效果如下:

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992751.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存