Android技术知识Android开发经验谈Android开发

Android传值Intent和Bundle区别

2019-03-06  本文已影响43人  TryEnough

原文: http://tryenough.com/android-intent-bundle


小伙伴问Android传值Intent和Bundle区别,特此总结下:

Intent与Bundle在传值上的区别

首先从使用上:

Intent方式:

假设需要将数据从页面A传递到B,然后再传递到C。

A页面中:

    Intent intent=new Intent(MainActivity.this,BActivity.class);
    intent.putExtra("String","MainActivity中的值");
    intent.putExtra("int",11);
    startActivity(intent);

B页面中:

需要先在B页面中接收数据

    Intent intent = getIntent();
    string = intent.getStringExtra("String");
    key = intent.getIntExtra("int",0);

然后再发数据到C页面

原文: http://tryenough.com/android-intent-bundle

    Intent intent=new Intent(BActivity.this,CActivity.class);
    intent.putExtra("String1",string);
    intent.putExtra("int1",key);
    intent.putExtra("boolean",true);
    startActivity(intent);

可以看到,使用的时候不方便的地方是需要在B页面将数据一条条取出来然后再一条条传输给C页面。

而使用Bundle的话,在B页面可以直接取出传输的Bundle对象然后传输给C页面。

Bundle方式:
A页面中:

    Intent intent = new Intent(MainActivity.this, BActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("String","MainActivity中的值");
    bundle.putInt("int",11);
    intent.putExtra("bundle",bundle);
    startActivity(intent);

原文: http://tryenough.com/android-intent-bundle

在B页面接收数据:

Intent intent = getIntent();
bundle=intent.getBundleExtra("bundle");

然后在B页面中发送数据:

    Intent intent=new Intent(BActivity.this,CActivity.class);
    //可以传给CActivity额外的值
    bundle.putBoolean("boolean",true);
    intent.putExtra("bundle1",bundle);
    startActivity(intent);

总结:

Bundle可对对象进行操作,而Intent是不可以。Bundle相对于Intent拥有更多的接口,用起来比较灵活,但是使用Bundle也还是需要借助Intent才可以完成数据传递总之,Bundle旨在存储数据,而Intent旨在传值。

原文: http://tryenough.com/android-intent-bundle

然后看下intent的put方法源码:

    public @NonNull Intent putExtra(String name, Parcelable value) {
        if (mExtras == null) {
            mExtras = new Bundle();
        }
        mExtras.putParcelable(name, value);
        return this;
    }

可以看到其实内部也是使用的Bundle来传输的数据。

题外话

为什么Bundle不直接使用Hashmap代替呢?

原文: http://tryenough.com/android-intent-bundle

上一篇 下一篇

猜你喜欢

热点阅读