Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 兩個 Activity 之間的資料傳遞方法

編輯:進階開發

初學 Android 時,畫面之間傳遞資料是很實用的技能。本文整理兩種常見做法:透過 Intent 傳遞,以及透過 SharedPreferences 暫存。

一、透過 Intent 傳遞

傳字串時,在來源 Activity 中:

String text = "hello";
Intent intent1 = new Intent(ActivityMain.this, Activity2.class);
intent1.putExtra("activity1", text);
startActivity(intent1);

傳物件時,物件需實作 Serializable 介面,再用 Bundle 包裝:

Bundle mbundle = new Bundle();
mbundle.putSerializable("user", userList.get(position));
Intent in = new Intent(getApplicationContext(), activity2.class);
in.putExtras(mbundle);
startActivity(in);

在目標 Activity 中接收:

// 接收字串
Bundle extras = getIntent().getExtras();
if (extras != null) { textView.setText(extras.getString("activity1")); }
// 接收物件
Bundle bundel = getIntent().getExtras();
User user = (User) bundel.get("user");

二、透過 SharedPreferences

在來源 Activity 中寫入:

SharedPreferences sp = getSharedPreferences("textinfo", 0);
Editor editor = sp.edit();
editor.putString("text", "hello");
editor.commit();
startActivity(new Intent(getApplicationContext(), activity2.class));

在目標 Activity 中讀取:

SharedPreferences share = getSharedPreferences("textinfo", 0);
String text = share.getString("text", null);
msgTextView.setText(text);

Intent 適合即時、一次性的資料傳遞;SharedPreferences 則適合需要持久保存的簡單鍵值資料。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved