Android Hello World實例介紹
一、安裝開發平臺和工具
1、Android SDK安裝;
2、Eclipse(ADT Plugins)安裝;
二、AVD創建
打開Android SDK And AVD Manger,創建一個AVD(Android Virtual Device)-虛擬設備(後續開發、調試用),假定版本爲2.1-update1;
三、創建一個Android Project
1、在Eclipse中選擇創建一個Android項目;
2、選擇與之前創建的AVD一樣的目標框架(Bulid Target):2.1-update1
3、各項屬性填寫如下:
- Project name: HelloAndroid
- Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD.
- Application name: Hello, Android
- Package name: com.example.helloandroid (可以自定義自己的命名空間)
- Create Activity: HelloAndroid
package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } }說明:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/>
利用這種方式,開發者可以快速的定義應用的UI框架,同時,該方式很好的實現了UI代碼和業務邏輯代碼的分離!
下面說明下上述XML元素的幾個屬性含義:
Attribute | Meaning |
---|---|
xmlns:android |
XML命名空間,必須包含。 |
android:id |
元素ID。該ID可以來自代碼中的View類ID或者其他XML Layout。 |
android:layout_width |
定義當前View的寬度(本例爲全屏寬度)。 |
android:layout_height |
定義當前View的高度。 |
android:text |
設置Textview元素要顯示的文本內容。本例中,定義了一個“串資源”來定義text。"hello"是在res/values/strings.xml中定義的一個元素。這是Android推薦的串資源定義方式,因爲這種方式在實現多語言等應用時會十分方便,將資源文件和程序代碼分離。 |
/res/layout/main.xml
文件,將上面的xml內容拷貝並保存。另外,我們打開res/values/strings.xml,
修改其內容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello, Android! I am coming!</string> <string name="app_name">Hello, Android</string> </resources>
最後,我們修改HelloAndroid類代碼如下:
package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
此時,我們去除了TextView實現,而是用setContentView(R.layout.main)來實現UI繪製。其中類R由ADT自動生成,用來索引和定義各類資源元素,不要手動修改。
package com.example.helloandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int textview=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }下面,我們重新保存應用並運行,效果如下:
至此,我們完成了Android上的第一個Hello
World,Enjoy IT!