Activity 数据交换的几种形式介绍

来源:互联网 发布:霜之哀伤淘宝 编辑:程序博客网 时间:2024/04/30 08:45

    有时候我们想要用Intent传递一个对象,或者List<Object>,那该怎么传递呢?这里就具体说下具体如何做:

    使用Intent传递List<Object>或对象都必须让该对象实现Serializable 接口,通过序列化传递数据

    public class IntentData implements Serializable{  }
 一、对象的传递与接收
    1.传递对象

Intent intent = new Intent(this, OtherActivity.class);IntentData data = new IntentData();// 实现 序列化 接口intent.putExtra("key", data); startActivity(intent);

           2.接收该对象

getIntent().getSerializableExtra("key");

   二、List<Object> 的传递与接收

            1.List<Object> 的传递

Intent intent = new Intent(this, OtherActivity.class);List<IntentData> list = new ArrayList<IntentData>();IntentData data = new IntentData();// 实现 序列化 接口list.add(data);intent.putExtra("key", (Serializable)list); startActivity(intent);

          2.List<Object> 的接收

//接收传递的listList dataLists = (List<IntentData>) getIntent().getSerializableExtra("key");

   同样我们也可以使用缓存类来传递数据,在启动下一个Activity的时候,将数据保存到缓存类,在启动的Activity中,再从缓存类中取出

/** * 数据缓存类 * @author shihao * */public class Data {public static IntentData data;public static IntentData getData() {return data;}public static void setData(IntentData data) {Data.data = data;}}
  类似的我们也可以用Application来传递数据

public class MyApp extends Application {private IntentData data;public IntentData getData() {return data;}public void setData(IntentData data) {this.data = data;}}

需要在配置文件AndroidManifest.xml中做一下修改

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme"        android:name="com.example.androidintent.MyApp">

0 0
原创粉丝点击