大家都知道Activity之间可以用Intent传递数据,android提供传递基本类型和序列化传递,这样的数据都可以通过Intent来传递了,
传对象可以让对象实体实现Serializable就可以了,那集合怎么来进行传递呢,最后发现创建对象存储集合可以实现。
先贴出存放集合的对象让其实现Serializable:
public class SerializableList<T> implements Serializable{
private List<T> list;
public List<T> getList(){
return list;
}
public void setList(List<T> list){
this.list=list;
}
}
需要存放的集合其单一对象也要实现Serializable:
public class Car implements Serializable{
private String id;
private String name;
public Car(String id,String name){
this.id=id;
this.name=name;
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getName(){
return name;
}
public void setId(String name){
this.name=name;
}
}
Intent传递集合:
List<Car> carList=new ArrayList<>();
carList.add(new Car("0","比亚迪 F3"));
carList.add(new Car("1","比亚迪 唐"));
SerializableList<Car> serList=new SerializableList<>();
serList.setList(carList);
Intent intent=new Intent(ThisActivity.this,OtherActivity.class);
intent.putExtra("serList", serList);
startActivity(intent);
在接收的activity中获取所传来的数据:
SerializableList<Car> serList= (SerializableList<Car>) getIntent().getSerializableExtra("serList");
List<Car> carList=serList.getList();
至此我们就得到了要传递的数据carList,自己用的这样的需求,也分享给大家,很简单不喜勿喷。哈哈~