首页 > 其他分享 >Activity与Fragment之间通信(二)——接口回调

Activity与Fragment之间通信(二)——接口回调

时间:2024-05-27 23:58:58浏览次数:13  
标签:Fragment Bundle 接口 Activity import android public

一。引言

上篇文章讲述了Activity和Fragment怎么样通过Bundle传递消息,这篇介绍如何通过接口回调实现通信。

首先,Bundle并不适用于任何通信情况,我们来看看Bundle通信的缺点:

(1)数据类型的限制:Bundle只能传递一些基本数据类型,如int,String等,无法直接传递自定义对象。

(2)繁琐的代码:在需要传递多个参数和数据时,使用Bundle需要大量重复代码。

(3)性能开销:每次使用Bundle进行数据传递时,都会进行序列化和反序列化。

(4)不适用大量数据传递。

所以,我们需要引入接口回调。

二。代码实例

例子:当点击按钮时,按钮下部的FrameLayout会显示从Activity传来的消息。

Activity给Fragment传递消息,需要定义一个接口,接口内部定义一个方法,Activity实现该接口,重写方法。Activity中调用Fragment中的方法,Fragment就可得到Activity传来的消息了。

Fragment中声明接口,并将接口传入构造方法中,以便MainActivity进行实例化。

(1)创建OnMessageListner接口

package com.example.activitytofragment2;

public interface OnMessageListner {
    void onMessageListener(String message);
}

(2)创建Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <Button
        android:id="@+id/btn_interface"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="通过接口回调将消息传递给Fragment"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment_interface"/>


</LinearLayout>

(3)创建MainActivity

package com.example.activitytofragment2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements OnMessageListner{
    private Button btnInterface;
    private InterfaceFragment interfaceFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        interfaceFragment = new InterfaceFragment(this); // 创建InterfaceFragment实例,并传递当前Activity作为参数
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_interface, interfaceFragment).commit(); // 将Fragment添加到Activity中
        btnInterface = findViewById(R.id.btn_interface);
        btnInterface.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessageToFragment("Hello from MainActivity");
            }
        });
    }

    private void sendMessageToFragment(String message) {
        interfaceFragment.displayMessage(message);
    }

    @Override
    public void onMessageListener(String message) {
        //这里可以用来处理来自Fragment的信息
    }


}

(4)创建fragment_interface.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=".InterfaceFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/tv_interface"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

(5)创建InterfaceFragment

package com.example.activitytofragment2;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class InterfaceFragment extends Fragment {
    private TextView tvInterface;
    private OnMessageListner onMessageListner;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_interface,container,false);
        tvInterface = view.findViewById(R.id.tv_interface);
        return view;
    }

    public InterfaceFragment(OnMessageListner onMessageListner) {
        this.onMessageListner = onMessageListner;
    }

    public void displayMessage(String message) {
        tvInterface.setText(message);
    }
}

标签:Fragment,Bundle,接口,Activity,import,android,public
From: https://blog.csdn.net/weixin_63424693/article/details/139250643

相关文章

  • 软件测试之接口自动化学习
    首先我们要知道什么是接口自动化测试?接口自动化测试是指使用自动化测试工具或脚本,通过模拟用户的操作来测试接口的正确性、稳定性和性能。通过自动化测试,可以提高测试效率、减少测试成本,并能够快速发现接口中的问题和缺陷。接口自动化测试可以对接口的输入和输出进行验证,检查......
  • 操作系统 实验18 批处理操作接口8:函数
    1、建立文件func2.sh,输出文件内容各行及行数脚本:#!/bin/bashecho-n"请输入一个文件名及路径:"readFILEstatisfile(){ locali=0 whilereadline do leti++ echo"$i$line" done<$FILE echo"$FILE有$i行"}echo"调用shell函数statisfile()&quo......
  • 【Postman接口测试】第一节.接口测试基础认识
    文章目录前言一、接口的基础   1.1什么是接口   1.2软件为什么需要接口   1.3为什么要做接口测试二、接口测试的基础   2.1接口测试介绍   2.2接口测试的实现方式三、接口返回数据和JSON详解四、接口测试协议详解总结前言一、......
  • json-server 快速搭建接口服务 使用教程
    json-server是一款小巧的接口模拟工具,一分钟内就能搭建一套Restful风格的API,尤其适合前端接口测试使用。只需指定一个json文件作为api的数据源即可,使用起来非常方便,30秒入门。进阶操作还支持分页,排序等操作,非常方便!开源地址主页地址:https://www.npmjs.com/package/js......
  • 亚马逊API实时数据接口,亚马逊商品详情数据接口采集助力高效查找采购低价货源
    亚马逊通过其API接口,为开发者提供了实时获取商品详情数据的能力,从而助力高效地查找和采购低价货源。在当今的电子商务领域,能够快速准确地获取产品信息是至关重要的。亚马逊API不仅使得这一过程自动化,还提高了操作的效率和准确性。下面将详细探究这些API如何工作以及它们如何帮......
  • 亚马逊API实时数据接口丨关键词搜索亚马逊商品列表数据接口丨亚马逊商品数据采集接口
    关键词搜索亚马逊商品列表数据接口通常涉及以下步骤11:关键词研究:首先,需要确定与您的产品相关的关键词。这可以通过使用亚马逊的自动搜索建议功能、GoogleAdwords、MerchantWords、KTD等关键词研究工具来完成。您还可以参考同类产品大卖家的详情页面,从他们的标题、描述、评论......
  • 调用三方接口,outputStream.write传参数中参数怎么写,在转化成字节数组之前,是A=a&B=b的
    当您调用第三方接口并通过OutputStream.write()方法发送参数时,如果接口期望的是application/x-www-form-urlencoded类型的参数(常见于POST请求中提交表单数据),那么您确实需要将参数转换成A=a&B=b这样的格式,然后再将这个字符串转换成字节数组。以下是转换和发送这种类型参数的步骤:......
  • 调用三方接口,outputStream.write传参数中参数怎么写
    当您调用一个第三方接口并需要使用OutputStream.write()方法发送数据时,您通常需要将数据转换为字节格式,因为write()方法接受的是字节(byte)、字节数组(byte[])或字节数组的一个子序列作为参数。以下是几种常见的情况和相应的示例:发送字节数组:如果您已经有了一个字节数组,您可以直接......
  • 接口报错.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework
    1、报文:.w.s.m.s.DefaultHandlerExceptionResolver:Resolved[org.springframework.http.converter.HttpMessageNotReadableException:JSONparseerror:Unexpectedcharacter('''(code39)):wasexpectingdouble-quotetostartfieldname;nestedex......
  • 基于翔云C#语言的身份证实名认证接口开发示例
    现如今,安全与便捷成为了互联网服务的两大关键词。为了进一步提升用户体验并加强网络安全管理,国内多家主流App近日宣布完成一项重要功能升级——集成身份证实名认证系接口。这一举措标志着用户在进行App注册时,将享受到更加高效、安全的身份验证体验。以往,用户在注册各类App......