> 編寫:[yuanfentiank789](https://github.com/yuanfentiank789) - 原文:[http://developer.android.com/training/basics/firstapp/starting-](http://developer.android.com/training/basics/firstapp/starting-activity.html)[activity](# "An activity represents a single screen with a user interface.").html
在完成上一課(建立簡單的用戶界面)后,我們已經擁有了顯示一個[activity](# "An activity represents a single screen with a user interface.")(一個界面)的app(應用),該[activity](# "An activity represents a single screen with a user interface.")包含了一個文本字段和一個按鈕。在這節課中,我們將添加一些新的代碼到`MyActivity`中,當用戶點擊發送(Send)按鈕時啟動一個新的[activity](# "An activity represents a single screen with a user interface.")。
### 響應Send(發送)按鈕
1 在Android Studio中打開res/layout目錄下的activity_my.xml 文件.
2 為 Button 標簽添加[android:onclick](http://developer.android.com/reference/android/view/View.html#attr_android:onClick)屬性.
res/layout/activity_my.xml
~~~
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
~~~
`android:onclick`屬性的值`"sendMessage"`即為用戶點擊屏幕按鈕時觸發方法的名字。
3 打開java/com.mycompany.myfirstapp目錄下MyActivity.java 文件.
4 在MyActivity.java 中添加sendMessage() 函數:
java/com.mycompany.myfirstapp/MyActivity.java
~~~
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
~~~
為使系統能夠將該方法(你剛在MyActivity.java中添加的sendMessage方法)與在`android:onClick`屬性中提供的方法名字匹配,它們的名字必須一致,特別需要注意的是,這個方法必須滿足以下條件:
- 是public函數
- 無返回值
- 參數唯一(為View類型,代表被點擊的視圖)
接下來,你可以在這個方法中編寫讀取文本內容,并將該內容傳到另一個[Activity](# "An activity represents a single screen with a user interface.")的代碼。
### 構建一個Intent
> [Intent](http://developer.android.com/reference/android/content/Intent.html)是在不同組件中(比如兩個[Activity](# "An activity represents a single screen with a user interface."))提供運行時綁定的對象。`Intent`代表一個應用"想去做什么事",你可以用它做各種各樣的任務,不過大部分的時候他們被用來啟動另一個[Activity](# "An activity represents a single screen with a user interface.")。更詳細的內容可以參考[Intents and Intent Filters](http://developer.android.com/guide/components/intents-filters.html)。
1 在MyActivity.java的`sendMessage()`方法中創建一個`Intent`并啟動名為`DisplayMessageActivity`的[Activity](# "An activity represents a single screen with a user interface."):
java/com.mycompany.myfirstapp/MyActivity.java
~~~
Intent intent = new Intent(this, DisplayMessageActivity.class);
~~~
> **Note**:如果使用的是類似Android Studio的IDE,這里對`DisplayMessageActivity`的引用會報錯,因為這個類還不存在;暫時先忽略這個錯誤,我們很快就要去創建這個類了。
在這個Intent構造函數中有兩個參數:
-
第一個參數是[Context](http://developer.android.com/reference/android/content/Context.html)(之所以用`this`是因為當前[Activity](# "An activity represents a single screen with a user interface.")是`Context`的子類)
-
接受系統發送[Intent](http://developer.android.com/reference/android/content/Intent.html)的應用組件的[Class](http://developer.android.com/reference/java/lang/Class.html)(在這個案例中,指將要被啟動的[activity](# "An activity represents a single screen with a user interface."))。
Android Studio會提示導入[Intent](http://developer.android.com/reference/android/content/Intent.html)類。
2 在文件開始處導入[Intent](http://developer.android.com/reference/android/content/Intent.html)類:
java/com.mycompany.myfirstapp/MyActivity.java
~~~
import android.content.Intent;
~~~
> **Tip:**在Android Studio中,按Alt + Enter 可以導入缺失的類(在Mac中使用option + return)
3 在`sendMessage()`方法里用[findViewById()](http://developer.android.com/reference/android/app/Activity.html#findViewById(int))方法得到[EditText](http://developer.android.com/reference/android/widget/EditText.html)元素.
java/com.mycompany.myfirstapp/MyActivity.java
~~~
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
}
~~~
4 在文件開始處導入EditText類.
在Android Studio中,按Alt + Enter 可以導入缺失的類(在Mac中使用option + return)
5 把EditText的文本內容關聯到一個本地 message 變量,并使用putExtra()方法把值傳給intent.
java/com.mycompany.myfirstapp/MyActivity.java
~~~
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
~~~
[Intent](http://developer.android.com/reference/android/content/Intent.html)可以攜帶稱作 _extras_ 的鍵-值對數據類型。 [putExtra()](http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Bundle))方法把鍵名作為第一個參數,把值作為第二個參數。
6 在MyActivity class,定義EXTRA_MESSAGE :
java/com.mycompany.myfirstapp/MyActivity.java
~~~
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
...
}
~~~
為讓新啟動的[activity](# "An activity represents a single screen with a user interface.")能查詢extra數據。定義key為一個public型的常量,通常使用應用程序包名作為前綴來定義鍵是很好的做法,這樣在應用程序與其他應用程序進行交互時仍可以確保鍵是唯一的。
7 在sendMessage()函數里,調用startActivity()完成新[activity](# "An activity represents a single screen with a user interface.")的啟動,現在完整的代碼應該是下面這個樣子:
java/com.mycompany.myfirstapp/MyActivity.java
~~~
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
~~~
運行這個方法,系統收到我們的請求后會實例化在`Intent`中指定的`Activity`,現在需要創建一個`DisplayMessageActivity`類使程序能夠執行起來。
### 創建第二個[Activity](# "An activity represents a single screen with a user interface.")
[Activity](# "An activity represents a single screen with a user interface.")所有子類都必須實現onCreate()方法。創建[activity](# "An activity represents a single screen with a user interface.")的實例時系統會調用該方式,此時必須用 setContentView()來定義[Activity](# "An activity represents a single screen with a user interface.")布局,以對[Activity](# "An activity represents a single screen with a user interface.")進行初始化。
### 使用Android Studio創建新的[Activity](# "An activity represents a single screen with a user interface.")
使用Android Studio創建的[activity](# "An activity represents a single screen with a user interface.")會實現一個默認的onCreate()方法.
1.
在Android Studio的java 目錄, 選擇包名 **com.mycompany.myfirstapp**,右鍵選擇 **New > [Activity](# "An activity represents a single screen with a user interface.") > Blank [Activity](# "An activity represents a single screen with a user interface.")**.
1.
在**Choose options**窗口,配置[activity](# "An activity represents a single screen with a user interface."):
- **[Activity](# "An activity represents a single screen with a user interface.") Name**: DisplayMessageActivity
**Layout Name**: activity_display_message
**Title**: My Message
**Hierarchical Parent**: com.mycompany.myfirstapp.MyActivity
Package name: com.mycompany.myfirstapp點擊 **Finish**.

3 打開DisplayMessageActivity.java文件,此類已經實現了onCreate()方法,稍后需要更新此方法。另外還有一個onOptionsItemSelected()方法,用來處理action bar的點擊行為。暫時保留這兩個方法不變。
4 由于這個應用程序并不需要onCreateOptionsMenu(),直接刪除這個方法。
如果使用 Android Studio開發,現在已經可以點擊Send按鈕啟動這個[activity](# "An activity represents a single screen with a user interface.")了,但顯示的仍然是模板提供的默認內容"Hello world",稍后修改顯示自定義的文本內容。
### 使用命令行創建[activity](# "An activity represents a single screen with a user interface.")
如果使用命令行工具創建[activity](# "An activity represents a single screen with a user interface."),按如下步驟操作:
1 在工程的src/目錄下,緊挨著MyActivity.java創建一個新文件DisplayMessageActivity.java.
2 寫入如下代碼:
~~~
public class DisplayMessageActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
~~~
> **Note**:如果使用的IDE不是 Android Studio,工程中可能不會包含由`setContentView()`請求的`activity_display_message` layout,但這沒關系,因為等下會修改這個方法。
3 把新[Activity](# "An activity represents a single screen with a user interface.")的標題添加到strings.xml文件:
~~~
<resources>
...
<string name="title_activity_display_message">My Message</string>
</resources>
~~~
4 在 AndroidManifest.xml的Application 標簽內為 DisplayMessageActivity添加 標簽,如下:
~~~
<application ... >
...
<activity
android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.mycompany.myfirstapp.MyActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.mycompany.myfirstapp.MyActivity" />
</activity>
</application>
~~~
`android:parentActivityName`屬性聲明了在應用程序中該[Activity](# "An activity represents a single screen with a user interface.")邏輯層面的父類[Activity](# "An activity represents a single screen with a user interface.")的名稱。 系統使用此值來實現默認導航操作,比如在Android 4.1(API level 16)或者更高版本中的[Up navigation](http://developer.android.com/design/patterns/navigation.html)。 使用[Support Library](http://developer.android.com/tools/support-library/index.html),如上所示的[`<meta-data>`](http://developer.android.com/guide/topics/manifest/meta-data-element.html)元素可以為安卓舊版本提供相同功能。
> **Note**:我們的Android SDK應該已經包含了最新的Android Support Library,它包含在ADT插件中。但如果用的是別的IDE,則需要在[ Adding Platforms and Packages ](http://developer.android.com/sdk/installing/adding-packages.html)中安裝。當Android Studio中使用模板時,Support Library會自動加入我們的工程中(在Android Dependencies中你以看到相應的JAR文件)。如果不使用Android Studio,就需要手動將Support Library添加到我們的工程中,參考[setting up the Support Library](http://developer.android.com/tools/support-library/setup.html)。
### 接收Intent
不管用戶導航到哪,每個[Activity](# "An activity represents a single screen with a user interface.")都是通過[Intent](http://developer.android.com/reference/android/content/Intent.html)被調用的。我們可以通過調用[getIntent()](http://developer.android.com/reference/android/app/Activity.html#getIntent())來獲取啟動[activity](# "An activity represents a single screen with a user interface.")的[Intent](http://developer.android.com/reference/android/content/Intent.html)及其包含的數據。
1 編輯java/com.mycompany.myfirstapp目錄下的DisplayMessageActivity.java文件.
2 刪除onCreate()方法中下面一行:
~~~
setContentView(R.layout.activity_display_message);
~~~
3 得到intent 并賦值給本地變量.
~~~
Intent intent = getIntent();
~~~
4 為Intent導入包.
在Android Studio中,按Alt + Enter 可以導入缺失的類(在Mac中使用option + return).
5 調用 getStringExtra()提取從 MyActivity 傳遞過來的消息.
~~~
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
~~~
### 顯示文本
1 在onCreate() 方法中, 創建一個 TextView 對象.
~~~
TextView textView = new TextView(this);
~~~
2 設置文本字體大小和內容.
~~~
textView.setTextSize(40);
textView.setText(message);
~~~
3 通過調用[activity](# "An activity represents a single screen with a user interface.")的setContentView()把TextView作為[activity](# "An activity represents a single screen with a user interface.")布局的根視圖.
~~~
setContentView(textView);
~~~
4 為TextView 導入包.
在Android Studio中,按Alt + Enter 可以導入缺失的類(在Mac中使用option + return).
DisplayMessageActivity的完整onCreate()方法應該如下:
~~~
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
~~~
現在你可以運行app,在文本中輸入信息,點擊Send(發送)按鈕,ok,現在就可以在第二[Activity](# "An activity represents a single screen with a user interface.")上看到發送過來信息了。如圖:

到此為止,已經創建好我們的第一個Android應用了!
- 序言
- Android入門基礎:從這里開始
- 建立第一個App
- 創建Android項目
- 執行Android程序
- 建立簡單的用戶界面
- 啟動其他的Activity
- 添加ActionBar
- 建立ActionBar
- 添加Action按鈕
- 自定義ActionBar的風格
- ActionBar的覆蓋層疊
- 兼容不同的設備
- 適配不同的語言
- 適配不同的屏幕
- 適配不同的系統版本
- 管理Activity的生命周期
- 啟動與銷毀Activity
- 暫停與恢復Activity
- 停止與重啟Activity
- 重新創建Activity
- 使用Fragment建立動態的UI
- 創建一個Fragment
- 建立靈活動態的UI
- Fragments之間的交互
- 數據保存
- 保存到Preference
- 保存到文件
- 保存到數據庫
- 與其他應用的交互
- Intent的發送
- 接收Activity返回的結果
- Intent過濾
- Android分享操作
- 分享簡單的數據
- 給其他App發送簡單的數據
- 接收從其他App返回的數據
- 給ActionBar增加分享功能
- 分享文件
- 建立文件分享
- 分享文件
- 請求分享一個文件
- 獲取文件信息
- 使用NFC分享文件
- 發送文件給其他設備
- 接收其他設備的文件
- Android多媒體
- 管理音頻播放
- 控制音量與音頻播放
- 管理音頻焦點
- 兼容音頻輸出設備
- 拍照
- 簡單的拍照
- 簡單的錄像
- 控制相機硬件
- 打印
- 打印照片
- 打印HTML文檔
- 打印自定義文檔
- Android圖像與動畫
- 高效顯示Bitmap
- 高效加載大圖
- 非UI線程處理Bitmap
- 緩存Bitmap
- 管理Bitmap的內存
- 在UI上顯示Bitmap
- 使用OpenGL ES顯示圖像
- 建立OpenGL ES的環境
- 定義Shapes
- 繪制Shapes
- 運用投影與相機視圖
- 添加移動
- 響應觸摸事件
- 添加動畫
- View間漸變
- 使用ViewPager實現屏幕側滑
- 展示卡片翻轉動畫
- 縮放View
- 布局變更動畫
- Android網絡連接與云服務
- 無線連接設備
- 使得網絡服務可發現
- 使用WiFi建立P2P連接
- 使用WiFi P2P服務
- 執行網絡操作
- 連接到網絡
- 管理網絡
- 解析XML數據
- 高效下載
- 為網絡訪問更加高效而優化下載
- 最小化更新操作的影響
- 避免下載多余的數據
- 根據網絡類型改變下載模式
- 云同步
- 使用備份API
- 使用Google Cloud Messaging
- 解決云同步的保存沖突
- 使用Sync Adapter傳輸數據
- 創建Stub授權器
- 創建Stub Content Provider
- 創建Sync Adpater
- 執行Sync Adpater
- 使用Volley執行網絡數據傳輸
- 發送簡單的網絡請求
- 建立請求隊列
- 創建標準的網絡請求
- 實現自定義的網絡請求
- Android聯系人與位置信息
- Android聯系人信息
- 獲取聯系人列表
- 獲取聯系人詳情
- 使用Intents修改聯系人信息
- 顯示聯系人頭像
- Android位置信息
- 獲取最后可知位置
- 獲取位置更新
- 顯示位置地址
- 創建和監視地理圍欄
- Android可穿戴應用
- 賦予Notification可穿戴特性
- 創建Notification
- 在Notifcation中接收語音輸入
- 為Notification添加顯示頁面
- 以Stack的方式顯示Notifications
- 創建可穿戴的應用
- 創建并運行可穿戴應用
- 創建自定義的布局
- 添加語音功能
- 打包可穿戴應用
- 通過藍牙進行調試
- 創建自定義的UI
- 定義Layouts
- 創建Cards
- 創建Lists
- 創建2D-Picker
- 創建確認界面
- 退出全屏的Activity
- 發送并同步數據
- 訪問可穿戴數據層
- 同步數據單元
- 傳輸資源
- 發送與接收消息
- 處理數據層的事件
- Android TV應用
- 創建TV應用
- 創建TV應用的第一步
- 處理TV硬件部分
- 創建TV的布局文件
- 創建TV的導航欄
- 創建TV播放應用
- 創建目錄瀏覽器
- 提供一個Card視圖
- 創建詳情頁
- 顯示正在播放卡片
- 幫助用戶在TV上探索內容
- TV上的推薦內容
- 使得TV App能夠被搜索
- 使用TV應用進行搜索
- 創建TV游戲應用
- 創建TV直播應用
- TV Apps Checklist
- Android企業級應用
- Ensuring Compatibility with Managed Profiles
- Implementing App Restrictions
- Building a Work Policy Controller
- Android交互設計
- 設計高效的導航
- 規劃屏幕界面與他們之間的關系
- 為多種大小的屏幕進行規劃
- 提供向下和橫向導航
- 提供向上和歷史導航
- 綜合:設計樣例 App
- 實現高效的導航
- 使用Tabs創建Swipe視圖
- 創建抽屜導航
- 提供向上的導航
- 提供向后的導航
- 實現向下的導航
- 通知提示用戶
- 建立Notification
- 當啟動Activity時保留導航
- 更新Notification
- 使用BigView風格
- 顯示Notification進度
- 增加搜索功能
- 建立搜索界面
- 保存并搜索數據
- 保持向下兼容
- 使得你的App內容可被Google搜索
- 為App內容開啟深度鏈接
- 為索引指定App內容
- Android界面設計
- 為多屏幕設計
- 兼容不同的屏幕大小
- 兼容不同的屏幕密度
- 實現可適應的UI
- 創建自定義View
- 創建自定義的View類
- 實現自定義View的繪制
- 使得View可交互
- 優化自定義View
- 創建向后兼容的UI
- 抽象新的APIs
- 代理至新的APIs
- 使用舊的APIs實現新API的效果
- 使用版本敏感的組件
- 實現輔助功能
- 開發輔助程序
- 開發輔助服務
- 管理系統UI
- 淡化系統Bar
- 隱藏系統Bar
- 隱藏導航Bar
- 全屏沉浸式應用
- 響應UI可見性的變化
- 創建使用Material Design的應用
- 開始使用Material Design
- 使用Material的主題
- 創建Lists與Cards
- 定義Shadows與Clipping視圖
- 使用Drawables
- 自定義動畫
- 維護兼容性
- Android用戶輸入
- 使用觸摸手勢
- 檢測常用的手勢
- 跟蹤手勢移動
- Scroll手勢動畫
- 處理多觸摸手勢
- 拖拽與縮放
- 管理ViewGroup中的觸摸事件
- 處理鍵盤輸入
- 指定輸入法類型
- 處理輸入法可見性
- 兼容鍵盤導航
- 處理按鍵動作
- 兼容游戲控制器
- 處理控制器輸入動作
- 支持不同的Android系統版本
- 支持多個控制器
- Android后臺任務
- 在IntentService中執行后臺任務
- 創建IntentService
- 發送工作任務到IntentService
- 報告后臺任務執行狀態
- 使用CursorLoader在后臺加載數據
- 使用CursorLoader執行查詢任務
- 處理查詢的結果
- 管理設備的喚醒狀態
- 保持設備的喚醒
- 制定重復定時的任務
- Android性能優化
- 管理應用的內存
- 代碼性能優化建議
- 提升Layout的性能
- 優化layout的層級
- 使用include標簽重用layouts
- 按需加載視圖
- 使得ListView滑動順暢
- 優化電池壽命
- 監測電量與充電狀態
- 判斷與監測Docking狀態
- 判斷與監測網絡連接狀態
- 根據需要操作Broadcast接受者
- 多線程操作
- 在一個線程中執行一段特定的代碼
- 為多線程創建線程池
- 啟動與停止線程池中的線程
- 與UI線程通信
- 避免出現程序無響應ANR
- JNI使用指南
- 優化多核處理器(SMP)下的Android程序
- Android安全與隱私
- Security Tips
- 使用HTTPS與SSL
- 為防止SSL漏洞而更新Security
- 使用設備管理條例增強安全性
- Android測試程序
- 測試你的Activity
- 建立測試環境
- 創建與執行測試用例
- 測試UI組件
- 創建單元測試
- 創建功能測試
- 術語表