編輯:Android 開發實例
登入畫面是許多 App 的第一道門。使用者可能要先登入 Facebook、微博或其他服務才能使用完整功能。本章從版面出發,依序完成輸入欄位、帳密比對,以及防止連續猜錯的保護機制。
先定義兩個 EditText 分別收集使用者名稱與密碼。密碼欄必須把 inputType 設為 textPassword,讓輸入內容以掩碼顯示:
<EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
接著定義一顆文字為 Login 的按鈕,並透過 onClick 屬性指定按下後要呼叫的方法名稱,之後在 Java 檔中實作該方法:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="login" android:text="@string/Login" />
在 Java 檔的 login() 方法中,以 getText() 取得輸入內容、toString() 轉為字串,再用 equals() 進行比對:
EditText username = (EditText)findViewById(R.id.editText1); EditText password = (EditText)findViewById(R.id.editText2); public void login(View view){ if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){ //correcct password }else{ //wrong password }
最後補上安全機制,避免使用者(或程式)無限度嘗試。做法是宣告一個計數變數,每次失敗就遞減,減到 0 時停用登入鈕:
int counter = 3; counter--; if(counter==0){ //disble the button, close the application e.t.c }
要提醒的是,這種本地計數只能算基本防呆。真正的帳號保護應在伺服器端實作,例如暫時鎖定、逐步延長冷卻時間、並記錄可疑來源。
以下範例做出一個只允許三次嘗試的登入畫面。可在實機或模擬器上執行。
| 步驟 | 做法 |
|---|---|
| 1 | 使用 Android Studio 建立專案並命名為 LoginScreen,Target SDK 對齊最新版 Android SDK。 |
| 2 | 修改 src/MainActivity.java,加入必要程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,加入對應的 XML 元件。 |
| 4 | 修改 res/values/string.xml,加入必要字串。 |
| 5 | 執行應用程式,選擇執行中的 Android 裝置安裝並驗證結果。 |
主活動 src/com.yiibai.loginscreen/MainActivity.java:
package com.example.loginscreen; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private EditText username=null; private EditText password=null; private TextView attempts; private Button login; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username = (EditText)findViewById(R.id.editText1); password = (EditText)findViewById(R.id.editText2); attempts = (TextView)findViewById(R.id.textView5); attempts.setText(Integer.toString(counter)); login = (Button)findViewById(R.id.button1); } public void login(View view){ if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){ Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show(); attempts.setBackgroundColor(Color.RED); counter--; attempts.setText(Integer.toString(counter)); if(counter==0){ login.setEnabled(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
版面配置 res/layout/activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textVew1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="18dp" android:text="@string/hello_world" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="50dp" android:text="@string/username" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textVew2" android:layout_marginLeft="32dp" android:layout_toRightOf="@+id/textView2" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/textVew3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textVew2" android:layout_marginTop="38dp" android:text="@string/password" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textVew3" android:layout_alignLeft="@+id/editText1" android:ems="10" android:inputType="textPassword" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText2" android:layout_centerHorizontal="true" android:layout_marginTop="94dp" android:onClick="login" android:text="@string/Login" /> <TextView android:id="@+id/textVew4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textVew3" android:layout_marginLeft="30dp" android:layout_marginTop="48dp" android:text="@string/attempts" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textVew1" android:layout_alignTop="@+id/textVew4" android:text="TextView" /> </RelativeLayout>
字串資源 res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LoginScreen</string> <string name="action_settings">Settings</string> <string name="hello_world">Login Screen</string> <string name="username">Username:</string> <string name="password">Password:</string> <string name="Login">Login:</string> <string name="attempts">Attempts Left:</string> </resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.loginscreen" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.loginscreen.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
將 App 安裝到 AVD 並啟動,一切設定正常時會出現如下的登入視窗:
在帳號欄輸入 admin,密碼欄輸入 Nimda(admin 反寫)後按下登入,驗證失敗:
連續失敗三次後,剩餘次數顯示為 0,登入按鈕被停用:
重新開啟 App,這次帳號與密碼皆輸入 admin 並按下登入,即登入成功:
實務上還有幾點值得補強。範例中的帳密寫死在程式碼內,僅供教學使用;正式專案應把驗證交由後端處理,並全程使用 HTTPS 傳輸。輸入體驗方面,密碼欄可加上 textNoSuggestions 避免輸入法聯想,帳號欄可依性質設定 textEmailAddress 等 inputType 以帶出合適鍵盤。流程方面,登入成功後應以 Intent 跳轉主畫面並呼叫 finish() 結束登入頁,以免使用者按返回鍵又回到登入畫面;若要在 App 內保存登入狀態,請使用加密後的 SharedPreferences 或 EncryptedSharedPreferences,切勿以純文字儲存密碼。
Android 本地化:讓同一支 App 在不同語言環境下說不同的話
一支上架的 App,可能同時被義大利米蘭的使用者、日本東京的使用者、德國柏林的用戶打開。若所有文字都寫死在程式碼裡,海外市場就等於放棄。Android 對這件事有非常漂亮
Android MediaPlayer 完整指南:播放控制、進度條與快轉倒轉
要在 App 裡播放音訊或影片,Android 提供了不少途徑,而 MediaPlayer 是最直覺的一個。它讓你以幾行程式碼就能控制內建媒體播放服務,完成播放、暫停、跳
用 JSONObject 拆解天氣 API:Android JSON 解析實戰
JSON(JavaScript Object Notation)雖然名字裡有 JavaScript,實際上它是一套語言中立的資料交換格式,也是目前 XML 最主流的替代方
Android NestedScrolling 完全實戰:打造自訂的嵌套滑動效果
從 Android 5.0 Lollipop 開始,官方提供了一整套 API 來支援嵌套滑動(Nested Scrolling);最新的 Support V4 包也做了向