前言:不知不觉工作已经八个月了,深感没学到什么东西啊,今年要努力了。但以后真的会用到android技术吗,根本回答不了这个问题,只能说,它是一个在任何事情都不成功的情况下,保命的根本而已,但技术还是要深通的。利用这两年时间把android搞精搞透。加油吧,少年
今天总结一下Fragment间的参数传递及结果返回的方法。
效果图:
1、点击“加载第二个Fragment按钮”,加载出第二个Fragment,同时传递过去参数:“从Fragment1传来的参数”这几个String;
2、当用户点击第二个Fragment中的几个图片时,将点中的结果返回给第一个Fragment,将用户的选择在第一个Fragment显示出来
一、基本架构搭建
首先,我们要把整个架构搭起来,然后再进行参数传递和回传
(一)、基本XML构建:
根据上面的效果,大家很容易看到两个Fragment的布局:
1、Fragment1的布局:(fragment1.xml)
很简单,垂直布局,上面一个ImageView来盛装返回过来的图片结果,下面一个Button来用来点击加载第二个Fragment;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<ImageView
android:id="@+id/img_result"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="center"/>
<Button
android:id="@+id/load_fragment2_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="加载第二个Fragment"/>
</LinearLayout>
2、Fragment2的布局:(fragment2.xml)
这个也是垂直布局,上面的一个TextView用来盛装从Fragment1传过来的String参数,下面的几个ImageView用来显