首页 技术 正文
技术 2022年11月11日
0 收藏 616 点赞 2,857 浏览 1679 个字

不时的回过头来看看自己的Andriod学习、实践之路,总发现有些曾经不明确的,如今清楚缘由。也会发现一些之前没怎么关注的。如今看到了 ,很想去深刻了解的。

比方:Bundle。

在一个Activity的生命周期中,首先要运行的是onCreate方法

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_modifyheadphoto);
}

在默认情况下,上面红色部分 是 onCreate方法的參数 , 默认运行的方法, 都会自己主动加入,而这部分普通情况。我都不去关注。你呢?

今天,就来搞清楚这个Bundle的作用,以及和Intent的差别。

一、Bundle:A mapping from String values to various Parcelable types

键值对的集合

类继承关系:

java.lang.Object

     android.os.Bundle

Bundle类是一个final类:

public final class Bundle extends Objectimplements Parcelable Cloneable

作用:能够用作是两个Activity间的通讯。

使用方法:

①、装载数据:

Bundle mBundle = new Bundle();

mBundle.putString("DataTag", "要传过去的数据");

Intent intent = new Intent(); 

         intent.setClass(MainActivity.this, Destion.class);  

         intent.putExtras(mBundle);

②、目标Activity解析数据

Bundle bundle = getIntent().getExtras();  //得到传过来的bundle

String data = bundle.getString("DataTag");//读出数据

二、Intent的含义和作用 就略了。

。。直接上二者比較:

两个Activity之间传递数据,数据的附加有两种方式:

    一种是直接 intent.putxx();

     还有一种是  先bundle.putxx(), 然后再调用public Intent putExtras (Bundle extras)  加入bundle.

事实上两种的本质是一样的。

先看Intent的方法:

public Intent putExtra(String name, boolean value) { 

    if (mExtras == null) { 

        mExtras = new Bundle(); 

    } 

    mExtras.putBoolean(name, value); 

    return this; 

当中mExtras是intent内部定义的一个private Bundle变量。

能够看到,intent事实上是调用了bundle对应的put函数,也就是说,intent内部还是用bundle来实现数据传递的,仅仅是封装了一层而已。

而使用Bundle传值的话最后调用的方法:Intent.putExtras(Bundle extras):

public Intent putExtras(Bundle extras) { 

    if (mExtras == null) { 

        mExtras = new Bundle(); 

    } 

    mExtras.putAll(extras); 

    return this; 

能够看到。事实上是把之前那个bundle中的数据批量加入到intent内部的bundle中。

事实上是和上面的直接用Intent传键值对是一样的原理。

总之呢,Intent旨在数据传递,bundle旨在存取数据,当然intent也提供一部分数据的存取,但比起bundle就显得不专业。不灵活的多

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293