Android中activity与fragment通信

Android中activity与fragment通信

一、activity之间传值

  • 通过intent传递数据
  • 通过Application
  • 使用单例
  • 静态成员变量
  • 持久化(sqlite、share preference、file等)

1、通过intent传递数据

  • 直接传递,intent.putExtra(key, value)
  • 通过bundle,intent.putExtras(bundle);

注意:
①这两种都要求传递的对象必须可序列化(Parcelable、Serializable),特别注意对象中对象也要序列化
②Parcelable实现相对复杂
③关于Parcelable和Serializable,官方说法:

Serializable: it's error prone and horribly slow. So in general: stay away from Serializable if possible.

也就是说和Parcelable相比,Seriaizable容易出错并且速度相当慢。

④通过intent传递数据是有大小限制滴,超过限制,要么抛异常,要么新的Activity启动失败,所以还是很严重的啊。

2、Application

将数据保存在全局Application中,随整个应用的存在而存在,这样很多地方都能访问。

但是需要注意的是:
当由于某些原因(比如系统内存不足),我们的app会被系统强制杀死,此时再次点击进入应用时,系统会直接进入被杀死前的那个界面,制造一种从来没有被杀死的假象。那么问题来了,系统强制停止了应用,进程死了,那么再次启动时Application自然新的,那里边的数据自然木有啦,如果直接使用很可能报空指针或者其他错误。
因此还是要考虑好这种情况的:
使用时一定要做好非空判断
②如果数据为空,可以考虑逻辑上让应用直接返回到最初的activity,比如用 FLAG_ACTIVITY_CLEAR_TASK 或者 BroadcastReceiver 杀掉其他的activity。

3、使用单例
比如一种常见的写法:

public class DataHolder {
  private String data;
  public String getData() {
  return data;}
  public void setData(String data) {
  this.data = data;}
  private static final DataHolder holder = new DataHolder();
  public static DataHolder getInstance() {
  return holder;}
}

这样在启动activity之前:
DataHolder.getInstance().setData(data);
新的activity中获取数据:
String data = DataHolder.getInstance().getData();

4、静态Static

 public static final String SEX = "sex";

5、持久化数据

sqlite、share preference、file

二、fragment之间传值

三、activity与fragment之间传值

1、activity向fragment传值:采用bundle方式

activity布局:

<?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:background="@color/rainbow_yellow"
    android:orientation=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值