Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Design 系列(十二):用 TextInputLayout 打造智慧輸入框

編輯:關於 Android 程式設計

TextInputLayout 是 Android Design Support Library 中相當實用的一個元件,它能為輸入框加上浮動標籤與錯誤提示,讓表單的引導更直覺。本文透過一個小範例,示範如何監聽輸入內容並即時顯示驗證訊息。

版面配置:activity_input_text.xml

先在版面配置中放一個包著 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>

程式碼:TextInputActivity.java

在 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) 即可隱藏錯誤提示。

這套做法很適合用於帳號、密碼等需要即時驗證的表單欄位,讓使用者能第一時間知道輸入是否正確。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved