10.2Activity的数据传递

    科技2022-07-13  111

    Activity的数据传递

    1.基本数据类型的两种方式。


    第一种

    直接利用Intent.putExtra的方法

    存储代码如下

    Intent intent=new Intent(MainActivity.this,SecondActivity.class); intent.putExtra("key",number); startActivity(intent);

    读取代码如下

    if(getIntent()!=null){ String number= getIntent().getStringExtra("key_main"); textView.setText(String.valueOf(number)); }

    第二种

    利用Bundle存储以后将Bundle放在intent种

    存储代码如下

    Intent intent=new Intent(MainActivity.this,ThirdActivity.class); Bundle bundle=new Bundle(); bundle.putInt("key2",number); intent.putExtra("key1",bundle);

    读取代码如下

    if(getIntent()!=null){ Bundle bundle=getIntent().getBundleExtra("key1"); int number=bundle.getInt("key2"); textView.setText(String.valueOf(number));

    2.引用数据类型的两种方式


    第一种 :实现Serializable接口,用法简单但是效率低。

    存储代码如下

    Intent intent=new Intent(MainActivity.this,SecondActivity.class); intent.putExtra("person",new Person()); startActivity(intent);

    读取代码如下

    Person person=(Person)getIntent().getSerializableExtra("person"); textView.setText(person.getName());

    因为返回的是Serializable类型的,所以向下强转为Person。



    第二种:实现Parcelable接口,用法复杂但是效率高。

    存储代码如下

    User user = new User("shellhub", 23); Intent intent = new Intent(this, SecondActivity.class); intent.putExtra(KEY, user); startActivity(intent);

    读取代码如下

    User user = getIntent().getExtras().getParcelable(KEY);

    为什么这里没有强转呢?

    因为方法实现了泛型,所以不需要类型转换。

    源码如下:

    public <T extends Parcelable> T getParcelable(@Nullable String key) {
    Processed: 0.009, SQL: 8