歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 不同Activity間傳遞數據

Android 不同Activity間傳遞數據

日期:2017/3/1 10:52:16   编辑:Linux編程
方法一:通過Android.content.Intent傳遞數據,只能傳遞基類型

存儲數據
  1. // 方法一:用intent傳遞數據
  2. intent.putExtra("string", str);
讀取數據
  1. // 方法一:用intent傳遞數據
  2. Intent intent = this.getIntent();
  3. Bundle bundle = intent.getExtras();
  4. str += "Fonction 1: " + bundle.getString("string") + "\n";
方法二:通過android.content.SharedPreferences傳遞數據,只能傳遞基類型

存儲數據
  1. // 方法二:用SharedPreferences傳遞數據
  2. SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);
  3. SharedPreferences.Editor editor = preferences.edit();
  4. editor.putString("string", str);
  5. editor.commit();
讀取數據
  1. // 方法二:用SharedPreferences傳遞數據
  2. SharedPreferences preferences = this.getSharedPreferences("test", MODE_PRIVATE);
  3. str += "Fonction 2: " + preferences.getString("string", "not found") + "\n";
方法三:自定義繼承Application的類傳遞數據,可以傳遞基類型和自定義類型,需要在manifest中注冊

manifest中注冊
  1. <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="mytest.xml.MyApp">
自定義繼承Application的類
  1. public class MyApp extends Application {
  2. private String str;
  3. private Obj obj;
  4. public String getStr() {
  5. return str;
  6. }
  7. public void setStr(String str) {
  8. this.str = str;
  9. }
  10. public Obj getObj() {
  11. return obj;
  12. }
  13. public void setObj(Obj obj) {
  14. this.obj = obj;
  15. }
  16. }
存儲數據
  1. // 方法三:用Application自定義類傳遞數據
  2. MyApp app = (MyApp)getApplicationContext();
  3. app.setStr(str);
  4. app.setObj(obj);
讀取數據
  1. // 方法三:用Application自定義類傳遞數據
  2. MyApp app = (MyApp)this.getApplicationContext();
  3. str += "Fonction 3 (string): " + app.getStr() + "\n";
  4. str += "Fonction 3 (object): " + app.getObj().getMess(); // app.getObj返回自定義Obj類實例,getMess()方法返回類內定義的String內容
Copyright © Linux教程網 All Rights Reserved