【Android 入門指南】系列文章目錄:https://bit.ly/3TFgCzu
Android 線上課程教學影片:https://bit.ly/433Offj
本課程學習如何使用 Intent 傳遞整包資料。
若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:
範例名稱:Intent 傳遞整包資料
作者:HKT (侯光燦)
授權範圍:使用時必須註明出處且不得為商業目的之使用
範例下載點:點我下載
加入 Gson 依賴套件
dependencies{
...
...
...
implementation ("com.google.code.gson:gson:2.8.9")
}
data class Transfer(
val id: String, //交易 ID
val fromAccountId: Long, //轉帳來源 ID
val toAccountId: Long, //轉帳目標 ID
val amount: Double, //轉帳金額
val createdAt: String //轉帳時間
)
val transfer = Transfer(
id = "TX8437858372101",
fromAccountId = 66612345678,
toAccountId = 66612345777,
amount = 100.00,
createdAt = "2077/08/14"
)
val jsonString = Gson().toJson(transfer)
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra(TRANSFER_DATA, jsonString)
startActivity(intent)
...
...
...
val jsonString = intent.getStringExtra(MainActivity.TRANSFER_DATA)
displayTransferData(jsonString)
...
...
...
private fun displayTransferData(jsonString: String?) {
jsonString?.let {
val transfer = Gson().fromJson(it, Transfer::class.java)
with(binding) {
tvTxId.text = transfer?.id ?: ""
tvFromAccountId.text = transfer?.fromAccountId?.toString() ?: ""
tvToAccountId.text = transfer?.toAccountId?.toString() ?: ""
tvAmount.text = transfer?.amount?.toString() ?: ""
tvCreatedAt.text = transfer?.createdAt ?: ""
}
}
}