編輯:關於 Android 程式設計
把前面的元件知識串起來,做一個最陽春的登入畫面:兩個輸入框、一個按鈕,帳號密碼正確就跳提示,錯誤就在輸入框下方顯示紅字。
這裡有幾個新的屬性:android:textSize 控制字級(單位用 sp),android:textColor 設定文字顏色,android:layout_gravity="right" 讓按鈕靠右對齊。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- android:textSize="16sp" 設定字體大小 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="請輸入用戶名"
android:textSize="16sp"
android:textColor="#FFC0CB" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用戶名:" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="請輸入密碼"
android:textSize="16sp"
android:textColor="#FFC0CB" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="密碼:" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="登錄"
android:onClick="click" />
</LinearLayout>
這裡用的是 XML 的 android:onClick="click",所以 Activity 中要有一個名為 click 且接收 View 參數的方法。
package com.example.test_login;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText name;
private EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
}
public void click(View view) {
if (name.getText().toString().equals("abc")
&& password.getText().toString().equals("abc")) {
// Toast.makeText(內容, 顯示的文字, 持續時間)
Toast.makeText(MainActivity.this, "跳轉", Toast.LENGTH_SHORT).show();
} else {
// setError() 會在輸入框下方顯示提示,並加上警示圖示
name.setError("用戶名或密碼錯誤");
password.setError("用戶名或密碼錯誤");
}
}
}


輸入正確帳密並點擊後,畫面下方會彈出 Toast 提示。
用 setError 而不是 Toast 報錯。這是最能提升表單體驗的小技巧:錯誤訊息直接顯示在出錯的欄位下方,使用者一眼就知道要改哪裡,而且輸入框會自動帶上警示圖示。Toast 適合「全域性、短暫」的提示,欄位級的錯誤就該用 setError()。
記得在輸入後清除錯誤狀態。若加上 addTextChangedListener 在文字變動時呼叫 setError(null),使用者修改內容後提示就會消失,體驗更順。
當然,這個範例把帳密寫死在程式碼裡只是為了示範。真實專案中的登入一定要走伺服器驗證,密碼傳輸必須加密,憑證也不該以任何形式存在客戶端程式碼中。
Android 整合百度地圖 SDK:定位、覆蓋物、POI 檢索到路線規劃全流程
這篇把百度地圖 SDK 的常用能力串成一份可實作的筆記,涵蓋定位顯示、多覆蓋物、座標與地址互轉、POI 檢索、路線查詢與線路繪製。API 說明可參考 https://lb
Android 文件監控 FileObserver 深度解析
在之前的《Linux 文件系統 Inotify 機制》中,我們介紹了 Linux 對文件變更的監控過程。Android 在此基礎上封裝了一個 FileObserver 類
Activity 的界面是怎麼挂上窗口的:setContentView 源碼全流程追蹤
上一篇談 Handler 原理時,說到 Activity 啟動如何走到 onCreate。本篇接著從 onCreate 裡必寫的 setContentView 出發,把佈
Android Matrix 圖像變換全解:從 3×3 矩陣原理到代碼實踐
線性代數裡學過矩陣的基本運算,但真正把「矩陣如何變換圖像」用透,往往是在實際做圖形處理的時候。本文把理論推導與 android.graphics.Matrix 的用法串起