在网上经常看到有的朋友会为Activity中的不同Fragment之间的通信儿苦恼。现在,本文将对该问题进行详细的介绍。
在实际的移动应用开发中,我们经常想要一个Fragment跟另一个Fragment进行通信,例如,要基于某一个用户事件来改变内容。首先说明一点:Fragment之间是不能直接进行通信的,所有的Fragment间的通信都是通过跟关联的Activity来完成的。也就是说,通过Activity转一下,按java常规,转一下多是使用Interface实现的。这里我们需要在一个Fragment中定义一个接口,然后让宿主Activity继承该接口,覆写其中的方法来完成Fragment之间的通信和参数传递。下面将一步步地对该过程进行阐述。
第一步:加载Fragment
为了更方便直观的了解操作方法,在Activity中定义左右两个Fragment,其中在左边的Fragment中定义一个文本输入框和一个提交按钮。在输入框中输入信息后,点击提交按钮会在右侧的Fragment中定义好的文本控件中予以显示。本实例中采用的是静态加载的方式,具体的加载步骤可以参考书籍或网上资源,本文不再过多赘述。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:name="com.fragmenttest.LeftFragment"
android:id="@+id/fragment_left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=