編輯:初階開發
在 Android 裡,一個 Activity 就是一個獨立畫面。畫面之間的切換很類似網頁上的超連結——按下某個按鈕,就跳到另一個畫面。負責這件事的,是名為 Intent 的物件,意思正是「意圖」:你想做什麼,就描述給系統聽。
下面用登入流程做示範:在首頁輸入帳號密碼,按下登入後跳到第二個畫面,並把輸入的內容顯示出來。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userName = ((EditText) findViewById(R.id.et_name)).getText().toString();
String pwd = ((EditText) findViewById(R.id.et_pwd)).getText().toString();
Intent intent = new Intent();
intent.setClass(Activity1.this, LoginOK.class); // 指定從哪裡跳到哪裡
Bundle bundle = new Bundle(); // 傳值用的容器,用法近似 Map
bundle.putString("userName", userName);
bundle.putString("pwd", pwd);
intent.putExtras(bundle); // 把 Bundle 放進 Intent
startActivity(intent); // 執行跳轉
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginok);
// 取得上一頁傳來的 Bundle
Bundle bundle = this.getIntent().getExtras();
TextView okInfo = (TextView) findViewById(R.id.okinfo);
StringBuilder sb = new StringBuilder();
sb.append("登錄資訊為:\n");
sb.append("使用者名稱:");
sb.append(bundle.getString("userName")); // 以 key 取值
sb.append("\n");
sb.append("密碼:");
sb.append(bundle.getString("pwd"));
sb.append("\n");
okInfo.setText(sb.toString());
}
Android 應用預設只有一個 Activity,多一個就必須在 AndroidManifest.xml 裡宣告,否則跳轉時會丟出 ActivityNotFoundException:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="test.k"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Test1"
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 -->
<activity android:name="LoginOK" android:label="登錄結果顯示畫面"></activity>
</application>
</manifest>
setClass 與 setClassName。前者用 Class 物件指定目標,比較直覺;若跨套件呼叫,則用 setClassName(套件名, 類別名)。兩者都屬於「顯式 Intent」,也就是明確點名要開哪一個畫面。
Bundle 的限制。它只能裝基本型別、字串與實作 Parcelable/Serializable 的物件。若要傳自訂物件,記得實作 Parcelable。
取 Bundle 前先判空。getExtras() 有可能回傳 null,正式環境建議寫成 bundle != null ? bundle.getString("userName") : "",避免空指針。
AndroidManifest.xml 這個檔案的重要性遠大於它看起來的樣子——權限、Service、Receiver、Provider 全都在這裡宣告,值得另外花時間好好讀一遍。
Android 軟鍵盤彈出時的版面縮放行為與監聽技巧
Android 是為觸控螢幕設計的系統,點擊輸入框時會自動彈出軟鍵盤。但鍵盤一出現,可用高度就變少了——系統該如何處理這段被壓縮的空間?我們能不能自行控制?這是本文想釐清
Android 實作:Service、BroadcastReceiver 與 AlarmManager
本文以「定時停止播放音樂」為例,說明如何結合 Service、AlarmManager 與 BroadcastReceiver。當使用者設定時間後啟動 Service,S
Android 開啟、關閉與監聽飛行模式
不多說廢話,先看效果,再上代碼。 飛行模式的讀寫本質上是操作 Settings.System.AIRPLANE_MODE_ON 這個系統數據項,再配合廣播通知全系統狀
Android 架構詳解
Android 五層架構 Android 系統架構可分為 Linux Kernel、Android Runtime、Libraries、Application Fram