Android<Fragment之间的通信以及Fragment和Activity的通信>

本文介绍了一种在Android应用中实现不同Fragment及Activity间通信的方法。具体实现方式为:定义一个接口并在FragmentLeft中触发,Activity实现该接口并完成UI更新等操作,同时通知到FragmentRight进行相应更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.情景假设:

假设现在有一个需求,一个Activity中有FragmentLeft和FragmentRight的布局,在最下面有一个Textview的布局。

这里写图片描述

现在需要在FragmentLeft中的按钮被点击的时候,FragmentRight和Activity中的Textview做出响应,类似这种效果:

这里写图片描述

2.解决办法:

i.在FragmentLeft中定义一个接口:

 public interface ButtonClick {
        void sendTextToActivityAndFragmentRight(String data);
    }

ii.然后在Activity中去实现这个接口

在实现的接口中,可以写下你想做的操作,比如更新Activity的UI,以及通过

FragmentRight fragmentRight= (FragmentRight) getSupportFragmentManager().findFragmentById(R.id.fragment2);
        fragmentRight.updateText(data);

这个updateText方法在你的FragmentRight中去实现
iii.在FragmentLeft中声明一个接口的引用,然后在FragmentLeft中的Onattach(Context context)中获取这个接口的实例

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mlistener = (ButtonClick) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement ButtonClicked");
        }
    }

3.完整代码:
FragmentLeft:

package com.example.geekp.fragmentcommunication;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class FragmentLeft extends Fragment implements View.OnClickListener {
    private ButtonClick mlistener;
    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Button button5;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                mlistener.sendTextToActivityAndFragmentRight("按钮一被点击了");
                break;
            case R.id.button2:
                mlistener.sendTextToActivityAndFragmentRight("按钮二被点击了");
                break;
            case R.id.button3:
                mlistener.sendTextToActivityAndFragmentRight("按钮三被点击了");
                break;
            case R.id.button4:
                mlistener.sendTextToActivityAndFragmentRight("按钮四被点击了");
                break;
            case R.id.button5:
                mlistener.sendTextToActivityAndFragmentRight("按钮五被点击了");
                break;
            default:
                break;
        }
    }

    public interface ButtonClick {
        void sendTextToActivityAndFragmentRight(String data);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mlistener = (ButtonClick) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement ButtonClicked");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mlistener = null;//避免内存泄漏
        super.onDetach();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_left, container, false);
        button1 = (Button) view.findViewById(R.id.button1);
        button2 = (Button) view.findViewById(R.id.button2);
        button3 = (Button) view.findViewById(R.id.button3);
        button4 = (Button) view.findViewById(R.id.button4);
        button5 = (Button) view.findViewById(R.id.button5);
        //设置监听事件
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        button5.setOnClickListener(this);
        // Inflate the layout for this fragment
        return view;
    }


}

fragment_left.xml:

<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"
    android:background="@color/colorPrimary"
    tools:context="com.example.geekp.fragmentcommunication.FragmentLeft">

    <!-- TODO: Update blank fragment layout -->
    <Button
        android:layout_marginTop="40dp"
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮一" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮二" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮三" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮四" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮五" />
</LinearLayout>

FragmentRight:

package com.example.geekp.fragmentcommunication;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentRight extends Fragment {
    private  TextView textView;

    public FragmentRight() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_fragment_right, container, false);
        textView= (TextView) view.findViewById(R.id.textview);
        // Inflate the layout for this fragment
        return view;
    }

    public void updateText(String text) {
    textView.setText(text);
    }
}

fragment_right.xml:

<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"
    android:background="@color/colorAccent"
    tools:context="com.example.geekp.fragmentcommunication.FragmentRight">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="内容" />

</FrameLayout>

MainActivity:

package com.example.geekp.fragmentcommunication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FragmentLeft.ButtonClick{
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= (TextView) findViewById(R.id.textviewinactivity);
    }

    @Override
    public void sendTextToActivityAndFragmentRight(String data) {
        FragmentRight fragmentRight= (FragmentRight) getSupportFragmentManager().findFragmentById(R.id.fragment2);
        fragmentRight.updateText(data);
        textView.setText(data);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.geekp.fragmentcommunication.MainActivity">

    <fragment
        android:layout_width="100dp"
        android:layout_height="400dp"
        android:name="com.example.geekp.fragmentcommunication.FragmentLeft"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/fragment1" />

    <fragment
        android:layout_width="250dp"
        android:layout_height="400dp"
        android:name="com.example.geekp.fragmentcommunication.FragmentRight"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/fragment2" />

    <TextView
        android:id="@+id/textviewinactivity"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/fragment1" />
</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值