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

Material Design 實作:用 TextInputLayout 做出浮動標籤與錯誤提示

編輯:關於 Android 開發

上一篇談完了 NavigationView,這次要說的是表單裡最容易被低估的一個小元件:TextInputLayout。

它解決了什麼問題

TextInputLayout 只能作為 EditText 的父容器使用,不能單獨存在。它解決的是一個老問題:傳統做法把提示文字放在 android:hint,使用者一旦開始輸入,提示就消失了——你可能根本不記得這個欄位要填什麼。

有了 TextInputLayout,當使用者聚焦並輸入時,hint 文字會平滑上浮到輸入框上方,繼續保持可見;同時它还提供了一個標準化的錯誤提示位,可以顯示在輸入框下方。

使用步驟

1. 版面配置

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/usernameWrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Username"
            android:inputType="textEmailAddress" />
    </android.support.design.widget.TextInputLayout>
</RelativeLayout>

2. Java 端操作

取得 TextInputLayout 後,可以透過 getEditText() 直接拿到內部的 EditText,不必再用 findViewById 繞一圈。

final TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.usernameWrapper);
textInputLayout.setHint("Username");

EditText editText = textInputLayout.getEditText();
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (s.length() > 3) {
            // 這裡可以換成更完整的正則表達式校驗
            textInputLayout.setError("Password error");
            textInputLayout.setErrorEnabled(true);   // 必須在 setError 之後呼叫
        } else {
            textInputLayout.setErrorEnabled(false);  // 條件不滿足時要關閉
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { }

    @Override
    public void afterTextChanged(Editable s) { }
});

這裡有個容易踩的坑:setErrorEnabled(true) 一定要在 setError() 之後呼叫,順序顛倒的話錯誤提示不會如預期顯示。

自訂 hint 與 error 的字型樣式

浮動上去的 hint 與下方的 error 文字,各自有獨立的外觀屬性可以覆寫:

app:errorTextAppearance="@style/FloatingStyle"
app:hintTextAppearance="@style/FloatingStyle"

對應的樣式定義:

<style name="FloatingStyle" parent="@android:style/TextAppearance">
    <item name="android:textColor">@color/colorPrimaryDark</item>
    <item name="android:textSize">12sp</item>
</style>

小結

TextInputLayout 的價值不在於程式碼量少,而在於它把「標籤」與「錯誤回饋」這兩件表單設計中最常被偷工減料的事,變成了幾行宣告就能搞定的標準件。搭配 Material Design 的主色調,一個視覺與可用性都到位的輸入欄位就完成了。

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