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
<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" />
</RelativeLayout>
MyFragment1.java
/*
* $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
*web: http://blog.csdn.net/nuptboyzhb
*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
<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
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn1"
android:text="回调Activity" />
</RelativeLayout>
MyFragment2.java
/*
* $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
*web: http://blog.csdn.net/nuptboyzhb
*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;
}
}
回调接口:
/*
* $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
*web: http://blog.csdn.net/nuptboyzhb
*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
<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>
MainActivity.java
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中的方法
} }
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnVwdDEyMzQ1Njc4OQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
初始画面
切换到第二个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:Activity+Fragment及它们之间的数据交换(一)的更多相关文章
- Android:Activity+Fragment及它们之间的数据交换.
Android:Activity+Fragment及它们之间的数据交换 关于Fragment与Fragment.Activity通信的四种方式 比较好一点的Activity+Fragment及它们之间 ...
- [转]Android:Activity+Fragment及它们之间的数据交换(一)
2014-05-18 来源:Android:Activity+Fragment及它们之间的数据交换(一) 简介: 为什么要用Fragment?使用Fragment可以在一个Acti ...
- 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之间的数据交换
1. 不带数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceS ...
- 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是 ...
随机推荐
- 基于最新友盟开发文档,集成友盟分享功能,赋demo
集成准备 获取Appkey 快速集成 获取SDK,页面截图: 下载后打开 导入jar和res 添加回调Activity 微信 在包名目录下创建wxapi文件夹,新建一个名为WXEntryActivit ...
- 允许root用户登录ssh
使用普通用户登录Ubuntu系统,打开命令行窗口 更改root用户密码,命令:sudo passwd root 首先输入当前用户的密码 然后输入root账户的密码 确认root用户的密码 编辑ssh的 ...
- Qt如何学习(参考官方文档)
Designers who are familiar with web development can start with QML 一共有四种安装工具 You have following opti ...
- [BZOJ2095]Bridges
最大值最小,是二分 转化为判定问题:给定一个混合图,问是否存在欧拉回路 首先,有向图存在欧拉回路的充要条件是每个点的入度等于出度,现在我们有一个混合图,我们要做的就是给其中的无向边定向,使得它变成有向 ...
- 四. Java继承和多态3. 继承中的方法的覆盖和重载
在类继承中,子类可以修改从父类继承来的方法,也就是说子类能创建一个与父类方法有不同功能的方法,但具有相同的名称.返回值类型.参数列表. 如果在新类中定义一个方法,其名称.返回值类型和参数列表正好与父类 ...
- SQL语句原理与高效SQL语句(转)
做软件开发的programers,大部分都离不开跟数据库打交道,特别是erp开发的,跟数据库打交道更是频繁,存储过程动不动就是上千行,如果数据量大,人员流动大,那么还能保证下一段时间系统还能流畅的运行 ...
- Java加密技术(一)—— HMACSHA1 加密算法
HMACSHA1 是从 SHA1 哈希函数构造的一种键控哈希算法,被用作 HMAC(基于哈希的消息验证代码). 此 HMAC 进程将密钥与消息数据混合,使用哈希函数对混合结果进行哈希计算,将所得哈希值 ...
- 导出/导入Eclipse的workspace配置(备份Eclipse配置)
设置好workspace配置后可以将配置保存为 *.epf 文件. 进入 File -> Export : 选择 General -> Preferences ,下一步: 选择 Expor ...
- 关于BufferedInputStream和BufferedOutputStream的实现原理的理解
在介绍FileInputStream和FileOutputStream的例子中,使用了一个byte数组来作为数据读入的缓冲区,以文件存取为例,硬盘存取的速度远低于内存中的数据存取速度.为了减少对硬盘的 ...
- HTTP请求和响应2:方法(Method)
方法表明了client希望server对资源运行的动作.经常使用的方法包含:GET.HEAD.POST.PUT.TRACE.OPTIONS和DELETE,每一个server能够实现这些方法中的部分或者 ...