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

一。引言

上篇文章讲述了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);
    }
}

  • 20
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值