我们知道在两个fragment之间传递数据要通过activity,如果两个fragment之间发生了数据的传递,如果这时我们的屏幕发生翻转activity将会启动onCreate()方法,这时fragment中的状态和数据将会被重置而得不到保存,那么如果我们想要保存fragment的数据和状态,就需要用到接口回调的设计思想。
我们写一个例子一个activity中有两个fragment,左边的fragment有两个按钮,右边的fragment有一个textview,当左边的按钮被点击,右边的text的内容相应发生改变,左边的如果点击music按钮,右边则显示music,左边如果点击news按钮,右边则显示news。
xml如下:
<?xml version="1.0" encoding="utf-8"?>
<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="horizontal"
tools:context="com.wusen.myfragmentdemo.MainActivity">
<fragment
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:id="@+id/fragment_menu"
android:name="com.wusen.myfragmentdemo.MenuFragment&#