編輯:關於 Android 程式設計
多頁面應用一定會遇到「A 頁面把資料帶到 B 頁面」,以及「B 頁面處理完把結果送回 A」。Android 的做法是以 Intent 承載資料、Bundle 負責包裝,再用 startActivityForResult() 取得回傳。以下用一個完整範例走過整個流程。
package com.chaoyang.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 指定要啟動的元件
Intent intent = new Intent(MainActivity.this, TheOtherActivity.class);
// 等價寫法:
// intent.setClass(MainActivity.this, TheOtherActivity.class);
// intent.setComponent(new ComponentName(MainActivity.this, TheOtherActivity.class));
// 寫法一:直接 putExtra(看起來最簡潔)
// intent.putExtra("name", "dinglang");
// intent.putExtra("age", 22);
// 寫法二:先組 Bundle 再整體塞入
Bundle bundle = new Bundle();
bundle.putString("name", "dinglang");
bundle.putInt("age", 22);
intent.putExtras(bundle);
// 不需要回傳值時可直接用 startActivity(intent)
// 需要回傳值時改用 startActivityForResult,第二個參數是請求碼
startActivityForResult(intent, 100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(this, data.getStringExtra("result"), 1).show();
}
}
為什麼兩種寫法本質相同?因為 putExtra(String, String) 內部會檢查這個 Intent 是否已有 Bundle,沒有的話就幫你建一個,之後所有 extra 都放進同一個 Bundle 裡。看過原始碼就會發現兩條路殊途同歸。
package com.chaoyang.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TheOtherActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
// 取得啟動自己的 Intent
Intent intent = this.getIntent();
String name = intent.getStringExtra("name");
int age = intent.getExtras().getInt("age"); // 寫法二對應的取值方式
TextView textView = (TextView) this.findViewById(R.id.result);
textView.setText("姓名:" + name + " 年齡:" + age);
Button button = (Button) this.findViewById(R.id.close);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("result", "這是處理結果");
setResult(20, data); // 設定結果碼與回傳資料
finish(); // 關閉自己,回到上一頁
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打開 OtherActivity" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="這是 OtherActivity" />
<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="關閉 Activity" />
</LinearLayout>
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 未在清單檔註冊的 Activity 啟動時會直接丟 ActivityNotFoundException -->
<activity android:name=".TheOtherActivity" android:label="the other Activity" />
Bundle 的角色。它用來攜帶資料,概念上類似 Map,存放 key-value 形式的配對,並針對常見型別提供 putString()/getString()、putInt()/getInt() 等方法。內部實際上是用 HashMap<String, Object> 保存資料。它的價值在於可序列化、可跨進程傳遞,因此不只 Intent 用它,onSaveInstanceState() 也用它。
請求碼與結果碼。onActivityResult() 的第一個參數是請求碼,就是你呼叫 startActivityForResult() 時傳入的值,用來在多個可回傳的頁面中分辨「這次回來的是誰」;第二個參數是結果碼,由目標頁透過 setResult() 設定,用來標示處理的結果狀態。兩者都只是你自己定義的識別碼,和 HTTP 的 200/404 完全無關,依業務需求自行約定即可。
現代寫法。上述 API 至今仍可用,但官方已推薦改用 Activity Result API:註冊 registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), callback),可省掉請求碼常數與 onActivityResult() 的覆寫,也能避開整頁重啟時狀態遺失的問題。若資料只是要在同一個 Task 內共享,也可考慮 ViewModel 或 Fragment Result API。
Android 下拉菜單 Spinner 組件的實現方法
在 Android 中,下拉菜單對應 HTML 裡的 <select> 標籤,其關鍵在於呼叫 setDropDownViewResource 方法,以 XML
Android 網路資料儲存實作:呼叫 WebService 並用 Gson 解析 JSON
什麼是網路儲存 在實際專案中,把資料放在伺服器上的場景非常多。所謂網路儲存,就是資料存在遠端主機,App 端像訪問一個 URL 那樣去取,拿到回應後再解析成物件。雙方通常
Android Studio 2.2 布局編輯器使用指南
一、用布局編輯器搭建界面 在 Android Studio 的布局編輯器中,你可以直接把控件從組件板拖進視覺化畫布,而不必逐行手寫 XML。編輯器能即時預覽布局在不同版本
Android NDK 入門:用 JNI 從 Java 呼叫 C 函式
NDK 環境設定完成後,就能用 C/C++ 撰寫 Android 的效能關鍵程式碼。這篇用一個 HelloWorld 專案把整條鏈路走一遍:宣告 native 方法、產生