這篇文章要示範如何從無到有建立一個具有完整功能的Android App專案,完成後的程式執行畫面如下圖。使用者輸入「性別」和「年齡」之後,按下「確定」按鈕,程式會顯示一個建議。在操作的過程中,我們會學到許多Eclipse使用技巧,善用它們可以大大提升開發程式的效率,而且可以避免打錯字的情況,現在就一起動手吧!

Step 2. Eclipse中央的編輯視窗會自動開啟介面佈局檔activity_main.xml(或者也可以在路徑res/layout中找到該檔,再用滑鼠快按二下將它開啟),將編輯視窗中的「介面佈局檔」切換到Graphical Layout模式,用滑鼠右鍵點選程式畫面上方的Hello World …字串(它是一個TextView型態的介面元件),然後在彈出的功能表中選擇Delete將它刪除。


private View.OnClickListener btnOKOnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String strSex = mEdtSex.getText().toString();
int iAge = Integer.parseInt(mEdtAge.getText().toString());
String strSug = getString(R.string.result);
if (strSex.equals(getString(R.string.sex_male)))
if (iAge < 28)
strSug += getString(R.string.sug_not_hurry);
else if (iAge > 33)
strSug += getString(R.string.sug_get_married);
else
strSug += getString(R.string.sug_find_couple);
else
if (iAge < 25)
strSug += getString(R.string.sug_not_hurry);
else if (iAge > 30)
strSug += getString(R.string.sug_get_married);
else
strSug += getString(R.string.sug_find_couple);
mTxtR.setText(strSug);
}
public class MainActivity extends Activity {
private EditText mEdtSex, mEdtAge;
private Button mBtnOK;
private TextView mTxtR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEdtSex = (EditText) findViewById(R.id.edtSex);
mEdtAge = (EditText) findViewById(R.id.edtAge);
mBtnOK = (Button) findViewById(R.id.btnOK);
mTxtR = (TextView) findViewById(R.id.txtR);
mBtnOK.setOnClickListener(btnOKOnClick);
}
…(其它程式碼)
最後我們列出這個App專案的字串資源檔「res/values/strings.xml」:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">婚姻建議程式</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="sex">性別:</string>
<string name="age">年齡:</string>
<string name="btn_ok">確定</string>
<string name="result">建議:</string>
<string name="edt_sex_hint">(輸入性別)</string>
<string name="edt_age_hint">(輸入年齡)</string>
<string name="sug_not_hurry">還不急。</string>
<string name="sug_get_married">趕快結婚!</string>
<string name="sug_find_couple">開始找對象。</string>
<string name="sex_male">男</string>
現在我們可以執行這個程式,並且看到它的執行畫面。