在本執行個體以及接下來的執行個體中,我們將採取循序漸進的方式分步討論涉及到Android程式設計的方方面面,以例子的方式來展示如何設計以及開發Android應用;
本執行個體介紹的將是資源檔的設計以及代碼關聯,並且附帶畫面跳轉功能;
1. 選擇菜單File->New->Android Project,在接下來的彈出頁面,輸入如下項目:
project name: ExampleOne;
Build target選擇Android2.0;
Application name: ExampleOne
package name: com.example
Create Activity: MainActivity:
點擊Next->Finish完成項目搭建過程;
2. 設計新的資源檔:這裡說的資源檔時介面排版檔案,在eclipse->Package Explorer裡面開啟res->layout,其上點擊滑鼠右鍵,在彈出的菜單中New->Android XML File,在彈出的對話方塊中選擇Layout,並且在File中輸入second_layout.xml(特別注意資源檔名必須小寫)後點擊本頁的Finish,完成後看到一個資源layout XML檔案的編輯頁面,在黑視窗上點擊右鍵選擇【Add...】菜單分別添加TextView以及Button2個控制項(直接在框內輸入,每次加一個).
3. 構建畫面的Activity:點擊左邊的資源樹 選擇src->com.example上點擊滑鼠右鍵選擇New->Class,在彈出的對話方塊中Name:SecondLayoutActivity,在SuperClass欄目中輸入或者選擇android.app.Activity,點擊Finish即完成畫面類代碼自動產生;
4. 點擊左邊的資源樹 選擇AndroidManifest.xml並且雙擊,在右邊出現的視圖中選擇Application,在Application Nodes欄目中點擊右邊的【Add...】按鈕,在彈出的對話方塊中選擇"create a new element at the top level, in application", 點擊"OK"確認後在隨後的主畫面中右邊的Name*後面選擇並點擊【Browse...】按鈕,在彈出的對話方塊中輸入SecondLayoutActivity並且點擊OK,完成資源與代碼的對應添加。
5. 修改SecondLayoutActivity類中的產生代碼,將MainActivity中OnCreate拷貝過來 (也可在該類上使用滑鼠右鍵菜單並且選擇Source->Override/Implement methods...在彈出框中選擇onCreate()並且點擊OK) 並且將R.layout.main修改為R.layout.second_layout即可完成SecondLayoutActivity類的資源與運行時功能掛接。
6. 掛接2個畫面的代碼實現跳轉;
修改main.xml資源檔,添加一個Button,屬性如下(可在ecliple下面的Properties框中修改或直接改main.xml檔案):
Text: Go to next view
Id: @+id/GoToNextView
修改MainActivity.java類,加入如下函數:
private void find_and_modify_gotoNextView(){
Button button = (Button)findViewById(R.id.GoToNextView);
button.setOnClickListener(gotoNextView_listener);
}
private Button.OnClickListener gotoNextView_listener = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondLayoutActivity.class);
startActivity(intent);
}
};
並且修改已經存在的onCreate重載函數,在最後部分添加:
find_and_modify_gotoNextView();
修改second_layout.xml,將2個控制項屬性調整為如下:
TextView id: @+id/GoBackHint
TextView text: Click the button to go back.
Button id: @+id/TurnBack
Button text: Turn back...
調整完畢後修改後在SecondLayoutActivity中添加如下代碼:
private void find_and_modify_TurnbackButton() {
Button button = (Button) findViewById(R.id.TurnBack);
button.setOnClickListener(buttonTurnback_listener);
}
private Button.OnClickListener buttonTurnback_listener = new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
};
並且在onCreate()最後添加如下的程式碼:
find_and_modify_TurnbackButton();
7. 運行測試:
在ExampleOne點擊滑鼠右鍵Run As->Android Application,即可運行測試,看看2個頁面的跳轉結果;
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/jackxinxu2100/archive/2010/01/26/5257186.aspx