Intent 传递List<Object>

Intent可以传递序列化对象, 但要求实现ParcelableSerializable接口

Intent传递序列化对象有如下方法

public Intent putExtra(String name, Parcelable value)
public Intent putExtra(String name, Serializable value)

如果一次传递多个序列化对象, 可以放到一个集合里面一起传递.

intent.putExtra("key", (Serializable) list);

需要将list强转为Serializable
源码中可以看到ArrayList也是实现了Serializable接口的

public class ArrayList<E> extends AbstractList<E> implements Cloneable, Serializable, RandomAccess 

注意: Bean也需要序列化

public class Music implements Serializable {
    private String name;
    private String artist;

    public Music(String name, String artist) {
        this.name = name;
        this.artist = artist;
    }
}
List<Music> list = new ArrayList<>();
        list.add(new Music("Delicious Way", "Mai Kuraki"));
        list.add(new Music("STAND BY YOU", "Mai Kuraki"));
        Intent intent = new Intent();
        intent.putExtra("key", (Serializable) list);
        setResult(RESULT_OK, intent);
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            List<Music> musics = (List<Music>) data.getSerializableExtra("key");
            for (Music music : musics) {
                if (BuildConfig.DEBUG) Log.d("MainActivity", "music:" + music.toString());
            }
        }
    }

logcat中打印出

D/MainActivity: music:Music{name='Delicious Way', artist='Mai Kuraki'}
D/MainActivity: music:Music{name='STAND BY YOU', artist='Mai Kuraki'}

Bundle中同样可以put序列化对象, 对应的方法:

public void putSerializable(@Nullable String key, @Nullable Serializable value)
public void putParcelable(@Nullable String key, @Nullable Parcelable value)
public void putParcelableArray(@Nullable String key, @Nullable Parcelable[] value)
public void putParcelableArrayList(@Nullable String key,@Nullable ArrayList<? extends Parcelable> value)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值