Android 不同Activity间传递数据
Android 不同Activity间传递数据
方法一:通过Android.content.Intent传递数据,只能传递基类型存储数据
- // 方法一:用intent传递数据
- intent.putExtra("string", str);
- // 方法一:用intent传递数据
- Intent intent = this.getIntent();
- Bundle bundle = intent.getExtras();
- str += "Fonction 1: " + bundle.getString("string") + "\n";
存储数据
- // 方法二:用SharedPreferences传递数据
- SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putString("string", str);
- editor.commit();
- // 方法二:用SharedPreferences传递数据
- SharedPreferences preferences = this.getSharedPreferences("test", MODE_PRIVATE);
- str += "Fonction 2: " + preferences.getString("string", "not found") + "\n";
manifest中注册
- <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="mytest.xml.MyApp">
- public class MyApp extends Application {
- private String str;
- private Obj obj;
- public String getStr() {
- return str;
- }
- public void setStr(String str) {
- this.str = str;
- }
- public Obj getObj() {
- return obj;
- }
- public void setObj(Obj obj) {
- this.obj = obj;
- }
- }
- // 方法三:用Application自定义类传递数据
- MyApp app = (MyApp)getApplicationContext();
- app.setStr(str);
- app.setObj(obj);
- // 方法三:用Application自定义类传递数据
- MyApp app = (MyApp)this.getApplicationContext();
- str += "Fonction 3 (string): " + app.getStr() + "\n";
- str += "Fonction 3 (object): " + app.getObj().getMess(); // app.getObj返回自定义Obj类实例,getMess()方法返回类内定义的String内容
评论暂时关闭