編輯:關於 Android 程式設計
TextInputLayout 是 Android Design Support Library 中相當實用的一個元件,它能為輸入框加上浮動標籤與錯誤提示,讓表單的引導更直覺。本文透過一個小範例,示範如何監聽輸入內容並即時顯示驗證訊息。
先在版面配置中放一個包著 EditText 的 TextInputLayout。由於本範例主要展示 TextInputLayout 的用法,這裡的 EditText 直接放在垂直 LinearLayout 中即可:
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/activity_text_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.design.widget.TextInputLayout
android:id="@+id/text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用戶名" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
在 Activity 中,我們讓它實作 TextWatcher,藉此監聽 EditText 的內容變化,並在輸入長度不足時顯示錯誤提示:
package com.iwanghang.coordinatordemo;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
public class TextInputActivity extends AppCompatActivity implements TextWatcher {
TextInputLayout text_input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_input);
text_input = (TextInputLayout) findViewById(R.id.text_input);
// 監聽 EditText 的內容改變
// 需實作 beforeTextChanged、onTextChanged、afterTextChanged 三個方法
text_input.getEditText().addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() < 6) {
text_input.setError("用戶名必須為 6 位或以上");
text_input.setErrorEnabled(true);
} else {
text_input.setErrorEnabled(false);
}
}
}
TextInputLayout.getEditText() 取得內部的 EditText,再掛上 TextWatcher。setError() 設定提示文字,setErrorEnabled(true) 才會讓錯誤訊息真正顯示出來。setErrorEnabled(false) 即可隱藏錯誤提示。這套做法很適合用於帳號、密碼等需要即時驗證的表單欄位,讓使用者能第一時間知道輸入是否正確。
把 Android AVD 模擬器搬家:修改預設建立路徑的完整做法
用 Eclipse 建立的 Android AVD,預設會被放在使用者資料夾底下的 .android 目錄裡,而這個資料夾幾乎都在系統碟上。當你陸續建了十幾個不同 API
Android Intent 入門與匹配機制總結
Intent 是 Android 元件溝通的重要橋梁,雖然不屬於四大元件,卻經常用於啟動 Activity、Service 與傳送 Broadcast。理解 Intent
Volley 源碼入門(一):從 newRequestQueue 到快取與網路雙執行緒
做 Android 一年多下來,越發覺得網路請求是整個開發裡極重要的一塊。Volley 是 Google 官方帶的框架,於是決定好好啃一遍源碼,把它的邏輯理清楚。Voll
Android 小遊戲打飛機(三):為遊戲添加敵機
8 月 9 日,晴。「江城如畫裡,山曉望晴空。雨水夾明鏡,雙橋落彩虹。人煙寒橘柚,秋色老梧桐。」 上一篇已讓飛機載入子彈、音效及背景音樂,本篇主要為遊戲添加敵機。 本篇用