本文以一個簡單的實例為大家介紹Android編程的入門知識,該案例是屬于較早期的實例程序,讀者可以對比學習,全面的了解Android程序的演化,以加深對Android程序設計的理解。程序運行平臺為Android SDK 1.5 + Eclipse + ADT,Android跟J2ME最大的區別在于UI的不同,當然Android比J2ME多出很多東西,并且多出的是J2ME無法作對比的。剛開始做Android開發,很多人都是先寫個簡單的界面,再加點控制代碼,本文就是這樣。
本文實例所講述的是LinearLayout + Button + EditText + AlertDialog的簡單使用。
Activity以 LinearLayout排列,共用到兩個 LinearLayout,第一個是用于全窗體,第二個用于存放兩個Button,第二個 LinearLayout放在EditText控件下面。
以下給出main.xml的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
|
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < EditText android:text = "EditText01" android:layout_height = "wrap_content" android:layout_width = "fill_parent" android:id = "@+id/edtInput" ></ EditText > < LinearLayout android:id = "@+id/LinearLayout01" android:layout_height = "wrap_content" android:layout_width = "fill_parent" android:gravity = "center" > < Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Show" android:id = "@+id/btnShow" ></ Button > < Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Clear" android:id = "@+id/btnClear" ></ Button > </ LinearLayout > </ LinearLayout > |
main.xml用于 Activity的UI設計,目前設計起來的速度,比 J2ME上的LWUIT略快(兩者類似,Android提供了GUI設計工具),比WM上的.NET CF略慢(.NETCF 是RAD)。
接下來給出JAVA代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package com.studio.android; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ Button btnShow; Button btnClear; EditText edtInput; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); btnShow=(Button)findViewById(R.id.btnShow); //控件與代碼綁定 btnClear=(Button)findViewById(R.id.btnClear); //控件與代碼綁定 edtInput=(EditText)findViewById(R.id.edtInput); //控件與代碼綁定 btnShow.setOnClickListener( new ClickListener()); //使用點擊事件 btnClear.setOnClickListener( new ClickListener()); //使用點擊事件 } class ClickListener implements OnClickListener { public void onClick(View v) { if (v==btnShow) { new AlertDialog.Builder(HelloAndroid. this ) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle( "Information" ) .setMessage(edtInput.getText()) .show(); } else if (v==btnClear) { edtInput.setText( "HelloAndroid" ); } } } } |
剛開始Android的開發,界面設計是J2ME程序員的瓶頸之處,不過以后Android的開發工具會越來越智能化,期待 Netbeans 推出更好的 ADT出來(Netbeans目前已經有Android插件)。希望本文所述實例能對大家學習Android有一定的幫助。