[转]Android:Activity+Fragment及它们之间的数据交换(一)
- 2014-05-18 来源:Android:Activity+Fragment及它们之间的数据交换(一)
简介:
为什么要用Fragment?使用Fragment可以在一个Activity中实现不同的界面。Fragment与 Fragment之间的动画切换,远比Activity与Activity之间的动画切换变化方式多。很多时候,我们通过使用一个Activity,切换 多个Fragment。本次博客,主要列举一下Fragment与它的Activity之间进行数据交换的方式。
1.Fragment中通过getActivity()然后进行强制转化,调用Activity中的公有方法
((XXXXActivity)getActivity()).fun();
2.Activity在切换Fragment的时候,通过setArguments向Fragment传递参数,Fragment通过getArguments();获得从activity中传递过来的值
3.Activity实现一个接口,Fragment在onAttach方法中,将该Activity转化为该接口,在需要调用的时候回调。
注意:本Demo是通过FragmentManager来管理Fragment的,通过FragmentManager管理,我们创建Fragment和销毁Fragment的时候,可以通过栈的方式:
a.FragmentTransaction的add方法,添加一个Fragment
b.FragmentTransaction的popBackStack()弹出该Fragment
演示实例:
fragment1.xml
|
1
2
3
4
|
<relativelayout 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="#FFFFFFFF" 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.testfragment.MainActivity$PlaceholderFragment"> <textview android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:text="fragment1"> <button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tv" android:text="跳转到Fragment2"></button></textview></relativelayout> |
MyFragment1.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
/* * $filename: MyFragment.java,v $ * $Date: 2014-5-16 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;/* *@author: ZhengHaibo *mail: zhb931706659@126.com *2014-5-16 Nanjing,njupt,China */public class MyFragment1 extends Fragment { FragmentCallBack fragmentCallBack = null; Button btn; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment1, container, false); btn = (Button)rootView.findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub fragmentCallBack.callbackFun1(null); } }); return rootView; } @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); fragmentCallBack = (MainActivity)activity; }} |
fragment2.xml
|
1
2
3
4
5
6
|
<relativelayout 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="#FFFFFFFF" 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.testfragment.MainActivity$PlaceholderFragment"> <textview android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:text="fragment2"> <button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tv" android:text="直接调用Activity"> </button><button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btn1" android:text="回调Activity"></button></textview></relativelayout> |
MyFragment2.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
/* * $filename: MyFragment.java,v $ * $Date: 2014-5-16 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast;/* *@author: ZhengHaibo *mail: zhb931706659@126.com *2014-5-16 Nanjing,njupt,China */public class MyFragment2 extends Fragment { FragmentCallBack fragmentCallBack = null; Button btn1; Button btn2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment2, container, false); Bundle data = getArguments();//获得从activity中传递过来的值 Toast.makeText(getActivity(), data.getString("TEXT"), Toast.LENGTH_SHORT).show(); btn1 = (Button)rootView.findViewById(R.id.btn1); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 直接调用Activity中的方法 ((MainActivity)getActivity()).changeButtonColor(); } }); btn2 = (Button)rootView.findViewById(R.id.btn2); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 回调的方式 fragmentCallBack.callbackFun2(null); } }); return rootView; } @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); fragmentCallBack = (MainActivity)activity; }} |
回调接口:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/* * $filename: FragmentCallBack.java,v $ * $Date: 2014-5-16 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testfragment;import android.os.Bundle;/* *@author: ZhengHaibo *mail: zhb931706659@126.com *2014-5-16 Nanjing,njupt,China */public interface FragmentCallBack { public void callbackFun1(Bundle arg); public void callbackFun2(Bundle arg);} |
main.xml
|
1
2
3
4
|
<relativelayout 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:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin"> <button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:text="切换"> <relativelayout android:id="@+id/rl_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/btn"></relativelayout></button></relativelayout> |
MainActivity.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
package com.example.testfragment;import android.graphics.Color;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity implements FragmentCallBack{ private Button btn; private MyFragment1 fragment1; private MyFragment2 fragment2; private FragmentManager fragmentManager; private Fragment currentFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragment1 = new MyFragment1(); Bundle data = new Bundle(); data.putString("TEXT", "这是Activiy通过Bundle传递过来的值"); fragment1.setArguments(data);//通过Bundle向Activity中传递值 fragmentTransaction.add(R.id.rl_container,fragment1);//将fragment1设置到布局上 fragmentTransaction.addToBackStack(null); fragmentTransaction.commitAllowingStateLoss(); currentFragment = fragment1; //初始化button控件 btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(currentFragment instanceof MyFragment1){ switchFragment(); }else{//当前是fragment2,因此,只需要将fragment2出栈即可变成fragment1 fragmentManager.popBackStack(); currentFragment = fragment1; } } }); } /** * 切换Fragment */ private void switchFragment(){ if(null == fragment2){//可以避免切换的时候重复创建 fragment2 = new MyFragment2(); } Bundle data = new Bundle(); data.putString("TEXT", "传递给fragment2"); fragment2.setArguments(data); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragmentTransaction.add(R.id.rl_container,fragment2); fragmentTransaction.addToBackStack(null); fragmentTransaction.commitAllowingStateLoss(); currentFragment = fragment2; } public void changeButtonColor(){ btn.setBackgroundColor(Color.RED); } @Override public void callbackFun1(Bundle arg) { // TODO Auto-generated method stub switchFragment();//通过回调方式切换 } @Override public void callbackFun2(Bundle arg) { // TODO Auto-generated method stub changeButtonColor();//通过回调方式调用Activity中的方法 }} |

初始画面

切换到第二个Fragment之后,通过Fragment2回调,改变按钮背景后的截图。
注意:
1.直接在Fragment中通过getActivity然后强转Activity的方式调用Activity的方法,这个方式不推荐!因为这会使Fragment的适配性变差。
解决方法:在使用之前,使用instanceof 判断一下Activity的类型
2.FragmentTransaction通过使用setCustomAnimations方法,可以为Fragment的切换增添各种不同的动画。变化方式远比Activity与Activity之间的切换动画要多。
3.多个Fragment之间,可以通过Activity复用很多代码,提高效率。
4.我们还可以通过ViewPager来管理Fragment,通过Adapter添加多个Fragment,然后通过setcurrentitem进行切换。我们同样可以通过setArguments向Fragment传递数据。
Android Fragment传递参数_Fragment之间传值的两种方法
2014-11-22 14:49:02 By: dwtedx
在Activity中加载Fragment的时候、有时候要使用多个Fragment切换、并传值到另外一个Fragment、也就是说两个
Fragment之间进行参数的传递、查了很多资料、找到两种方法、一种是通过共同的Activity传递、这种方法是在Activity里面添加一个字
段、来临时保存要一些值
翻了一下Fragment的API、找到了另外一个方法来传递、就像Activity一样便捷的实现参数传递程序中的一段代码、是通过Bundle来传递的、相比之下第一种方法要简单一点
Fragment参数传递方法一
在Activity中定义一个字段、然后添加set和get方法、代码如下、mTitle就是要传递的参数、如果是传递对象、可以把mTitle换成一个对象即可
public class DemoActivity {
private String mTitle;
public String getmTitle() {
return mTitle;
}
public void setmTitle(String title) {
this.mTitle = title;
}
}
Fragment调用方法、需要注意的是在设值的时候要进行强转一下
((DemoActivity)getActivity()).getmTitle();
Fragment参数传递方法二
可以使用bundle进行参数传递、这样在两个Fragment跳转的时候就可以带上参数了、同样也可以传递一个复杂的对象
ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(""));
DemoFragment demoFragment = new DemoFragment();
Bundle bundle = new Bundle();
bundle.putString("key", "这是方法二");
demoFragment.setArguments(bundle);
ft.add(R.id.fragmentRoot, demoFragment, SEARCHPROJECT);
ft.commit();
在另外一个Fragment获取参数的方式只需要一个语句、key是自己定义的一个标识、参数的形式只要bundle能传递都可以实现
String string = getArguments().getString("key");
总结
从上面两种方法看来、方法一要简单一些、但个人觉得有点投机取巧、不过也很合Java的开发规范、如果是同一个Activity中要加载很多Fragment的话、这种方法无疑要简单很多
而方法二是使用了Android的Bundle传递的、这种方法应该更官方一点吧、不过在项目开发中、怎么实现简单就怎么来、也没太多关系。
[转]Android:Activity+Fragment及它们之间的数据交换(一)的更多相关文章
- Android:Activity+Fragment及它们之间的数据交换.
Android:Activity+Fragment及它们之间的数据交换 关于Fragment与Fragment.Activity通信的四种方式 比较好一点的Activity+Fragment及它们之间 ...
- Android:Activity+Fragment及它们之间的数据交换(一)
简单介绍: 为什么要用Fragment?使用Fragment能够在一个Activity中实现不同的界面. Fragment与Fragment之间的动画切换,远比Activity与Activity之间的 ...
- Android Fragment与Activity之间的数据交换(Fragment从Activity获取数据)
Fragment与Activity之间的数据交换,通常含有3: 一.Fragment从Activity获取数据(仅本文介绍了一个第一): 两.Activity从Fragment获取数据: 三.Frag ...
- MFC拆分窗口及它们之间的数据交换(转)
转自:http://blog.csdn.net/nuptboyzhb/article/details/7455471 源代码:http://download.csdn.net/detail/nuptb ...
- MFC拆分窗口及它们之间的数据交换
源代码:http://download.csdn.net/detail/nuptboyzhb/4221531 CSplitterWnd类 CSplitterWnd类提供一个分隔器窗口的功能,分隔器窗口 ...
- Flink task之间的数据交换
Flink中的数据交换是围绕着下面的原则设计的: 1.数据交换的控制流(即,为了启动交换而传递的消息)是由接收者发起的,就像原始的MapReduce一样. 2.用于数据交换的数据流,即通过电缆的实际数 ...
- Android -- Activity,Fragment lifecycle
Activity Lifecyce Fragment Lifecycle: 程序运行: 09-16 13:59:22.883 19022-19022/com.example.android.archi ...
- 【转】Android Activity/Fragment Lifecycle
原文来自:http://stormzhang.github.io/android/2014/08/08/activity-fragment-lifecycle/ 说Activity和Fragment是 ...
- Android两个Activity之间的数据交换
1. 不带数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceS ...
随机推荐
- 强连通图(最多加入几条边使得图仍为非强连通图)G - Strongly connected HDU - 4635
题目链接:https://cn.vjudge.net/contest/67418#problem/G 具体思路:首先用tarjan缩点,这个时候就会有很多个缩点,然后再选取一个含有点数最少,并且当前这 ...
- BeanPostProcessor的五大接口
BeanPostProcessor 关于对象初始化前后的回调. public interface BeanPostProcessor { //该方法在bean实例化完毕(且已经注入完毕),在after ...
- bootstrap分页查询传递中文参数到后台(get方式提交)
<!--分页 --> <div style="width: 380px; margin: 0 auto; margin-top: 50px;"> <u ...
- 安全测试===dos攻击和ddos攻击
Dos攻击: dos攻击是Denial of Service的简称,即拒绝服务,造成DoS的攻击行为被称为DoS攻击,其目的是使计算机或网络无法提供正常的服务 DoS攻击是指故意的攻击网络协议实现的缺 ...
- openjudge-NOI 2.6-1768 最大子矩阵
题目链接:http://noi.openjudge.cn/ch0206/1768/ 题解: 如果用O(n4)的算法肯定会炸,需要压缩掉一维的空间,只需要简单加和就好啦 例如,我们要对样例中第2-4行D ...
- python的sorted函数对字典按value进行排序
场景:词频统计时候,我们往往要对频率进行排序 sorted(iterable,key,reverse),sorted一共有iterable,key,reverse这三个参数.其中iterable表示可 ...
- gdb安装
1.卸载原有gdb 以root用户登录 1.1 查询原有gdb包名,执行命令: rpm -q gdb 1.2 卸载原有gdb包,假设gdb包名为gdb-7.0-0.4.16,执行命令:rpm - ...
- #题目:有10 台被监控主机、一台监控机,在监控机上编写脚本,一旦某台被监控机器/ 分区适用率大于80%, 就发邮件报警放到crontab 里面, 每10 分钟检查一次
#题目:有10 台被监控主机.一台监控机,在监控机上编写脚本,一旦某台被监控机器/ 分区适用率大于80%, 就发邮件报警放到crontab 里面, 每10 分钟检查一次 #测试机器:虚拟机Linux ...
- DBCP object created 日期 by the following code was never closed:
1.分析 看到标题 DBCP 首先想到的肯定是 数据库连接池哪方面有问题,那么先别着急去解决,不要一股脑就钻进逻辑代码中,然后启用调试就开始一步一步 的分析.我们首先要做的就是想,想想数据库连接池,在 ...
- 微信小程序-textarea中的文本读取以及换行问题
今天客户那边要求textarea中输入的问题可以按回车键换行,而我使用的是bindinput获取值,但是呢bindinput 处理函数的返回值并不会反映到 textarea 上,按回车键导致点击换行符 ...