栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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




    

    
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、学习中的笔记(提醒自己需要查阅已经封装好的架构方案)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/855356.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号