Material Design 系列之 TextInputLayout 開發詳解

2021-02-20 碼農專欄
前言

本文是 Material Design 系列第四篇:TextInputLayout 主要是作為 EditText 的容器,從而為 EditText 生成一個浮動的 Label,當用戶點擊 EditText 的時候,EditText 中的 hint 字符串會自動移到 EditText 的左上角。

TextInputLayout 的簡單使用,是 Google 推出的整個 Material Design 庫的一個縮影:Google 將 UI 視覺效果設計得華麗且流暢,同時代碼封裝更為優雅,開發者只需要在 layout.xml 中寫好布局文件,就可以輕鬆在手機屏幕上展現出魔法般的動畫效果,實在是妙不可言。

一、TextInputLayout 相關 API

TextInputLayout 控制項 API 官網列舉了很多,這裡只是整理出開發中常用屬性,每個方法對應相關 XML 屬性感興趣的可以查查官網文檔。

setCounterEnabled(boolean enabled)

在此布局中是否啟用了字符計數器功能。

setCounterMaxLength(int maxLength)

設置要在字符計數器上顯示的最大長度。

setBoxBackgroundColorResource(int boxBackgroundColorId)

設置用於填充框的背景色的資源。

setBoxStrokeColor(int boxStrokeColor)

設置輪廓框的筆觸顏色。

setCounterOverflowTextAppearance(int counterOverflowTextAppearance)

使用指定的 TextAppearance 資源設置溢出字符計數器的文本顏色和大小。

setCounterOverflowTextColor(ColorStateList counterOverflowTextColor)

使用 ColorStateList 設置溢出字符計數器的文本顏色。(此文本顏色優先於 counterOverflowTextAppearance 中設置的文本顏色)

setCounterTextAppearance(int counterTextAppearance)

使用指定的 TextAppearance 資源設置字符計數器的文本顏色和大小。

setCounterTextColor(ColorStateList counterTextColor)

使用 ColorStateList 設置字符計數器的文本顏色。(此文本顏色優先於 counterTextAppearance 中設置的文本顏色)

setErrorEnabled(boolean enabled)

在此布局中是否啟用了錯誤功能。

setErrorTextAppearance(int errorTextAppearance)

設置來自指定 TextAppearance 資源的錯誤消息的文本顏色和大小。

setErrorTextColor(ColorStateList errorTextColor)

設置錯誤消息在所有狀態下使用的文本顏色。

setHelperText(CharSequence helperText)

設置將在下方顯示的幫助消息 EditText。

setHelperTextColor(ColorStateList helperTextColor)

設置輔助狀態在所有狀態下使用的文本顏色。

setHelperTextEnabled(boolean enabled)

在此布局中是否啟用了輔助文本功能。

setHelperTextTextAppearance(int helperTextTextAppearance)

設置指定 TextAppearance 資源中的輔助文本的文本顏色和大小。

setHint(CharSequence hint)

設置要在浮動標籤中顯示的提示(如果啟用)。

setHintAnimationEnabled(boolean enabled)

是否獲取焦點的時候,hint 文本上移到左上角開啟動畫。

setHintEnabled(boolean enabled)

設置是否在此布局中啟用浮動標籤功能。

setHintTextAppearance(int resId)

從指定的 TextAppearance 資源設置摺疊的提示文本的顏色,大小,樣式。

setHintTextColor(ColorStateList hintTextColor)

從指定的 ColorStateList 資源設置摺疊的提示文本顏色。

setPasswordVisibilityToggleEnabled(boolean enabled)

啟用或禁用密碼可見性切換功能。

二、TextInputLayout 使用詳解1、基本使用布局文件中只需要在 EditText 外層包裹一層 TextInputLayout 布局即可
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/userInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Username">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />

</com.google.android.material.textfield.TextInputLayout>

2、開啟錯誤提示

設置文本框輸入最大長度,並且開啟錯誤提示,當文本框輸入文本長度超出時,報錯顯示。

// 開啟錯誤提示
userInputLayout.setErrorEnabled(true);
// 開啟計數
userInputLayout.setCounterEnabled(true);
// 設置輸入最大長度
userInputLayout.setCounterMaxLength(10);

3、自定義浮動標籤字體樣式

默認浮動標籤樣式跟 APP 主題色 colorAccent 色值一致,所以需要自定義樣式,修改標籤字體大小和顏色

<style name="hintAppearence" parent="TextAppearance.AppCompat">
    <item name="android:textSize">14dp</item>
    <item name="android:textColor">@color/colorPrimary</item>
</style>

使用 setHintTextAppearance()方法加載自定義樣式
userInputLayout.setHintTextAppearance(R.style.hintAppearence);

如圖所示,Username 文本框是自定義樣式效果,Password 文本框是系統默認效果

TextInputLayout 中所有關於樣式的設置方式都採用這種方式,所以這裡只舉例一種,其他屬性直接照搬即可使用

4、密碼可見性切換

APP 登錄界面密碼框經常會遇到最右邊有一個「小眼睛」圖標,點擊可以切換密碼是否可見,以前我們實現時,使用一個 ImageView,然後根據點擊事件判斷標記位更新文本框的內容。現在使用 TextInputLayout 只需要一行代碼即可輕鬆實現。

這裡使用 XML 屬性實現,對應的 setPasswordVisibilityToggleEnabled(boolean enabled) 方法

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:hint="Password"
    app:counterOverflowTextAppearance="@style/hintAppearence"
    app:hintTextAppearance="@style/hintAppearence"
    app:passwordToggleEnabled="true">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/ic_baseline_lock_24"
        android:drawablePadding="8dp"
        android:inputType="textPassword"
        android:textSize="14dp" />

</com.google.android.material.textfield.TextInputLayout>

以上文本框左邊的 icon 使用 EditText 的android:drawableStart屬性添加

5、文本框輸入校驗

一般情況下,APP 用戶名稱輸入都會有校驗功能,本文以用戶名長度不大於 10 為例,如果超出時,輸入框底部報錯提示。

採用EditText.addTextChangedListener()方法實現,相信大家對這個監聽方法並不陌生,因為沒有 TextInputLayout 之前,這個應該是最常用的方式了。

注意:TextInputLayout.getEditText()方法獲取的就是內部的 EditText 控制項,所以不需要在 Activity 中在 findViewById 初始化 View

userInputLayout.getEditText().addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // 文本變化前調用
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // 文本發生變化時調用
    }

    @Override
    public void afterTextChanged(Editable s) {
        // 文本發生變化後調用
        if(userInputLayout.getEditText().getText().toString().trim().length()>10){
            userInputLayout.setError("用戶名長度超出限制");
        }else{
            userInputLayout.setError(null);
        }
    }
});

以上五種使用方式應該是開發過程中最常見的功能了,官網關於 TextInputLayout 屬性太多了,好多屬性我自己到現在都沒理解幹什麼的。不過只要掌握開發中這些常用的屬性就足夠了,TextInputLayout 底層實現了 LinearLayout,感興趣的朋友可以查看閱讀源碼深入學習。

源碼下載:https://github.com/jaynm888/MaterialDesign-master.git

源碼包含 Material Design 系列控制項集合,定時更新,敬請期待!

三、總結

本片文章已經是 Material Design 系列第四篇了,我會堅持把 Material Design 系列控制項全部介紹完畢,最後會將所有的 Demo 整合一套源碼分享給大家,敬請期待!相信看完我的博客對你學習 Material Design UI 控制項有一定的幫助,因為我會把每個控制項開發中的基本使用詳細講解,簡單易懂。

我的微信:Jaynm888

歡迎點評,誠邀 Android 程式設計師加入微信交流群,公眾號回復加群或者加我微信邀請入群。

相關焦點

  • ConstraintLayout的崛起之路
    文淑  的博客地址:https://blog.csdn.net/u012551350為啥會取這個標題,絕不是為了噱頭,源於最近看了一部國產漫畫一武庚紀2,劇情和畫質都非常棒的良心之作,且看武庚的崛起 。。。
  • ConstraintLayout,看完一篇真的就夠了麼?
    android:text="World"    app:layout_constraintBaseline_toBaselineOf="@id/tvHello"    app:layout_constraintLeft_toRightOf="@+id/tvHello"/>此時界面就如願了,比Relativelayout方便多了。
  • input輸入框如何快速進行規則校驗
    input輸入框是日常前端開發過程中經常會遇到的,輸入框是為了進行用戶交互,用戶提交或輸入數據,那麼在安全方面我們要做好把控工作,通常我們會制定規則來限制用戶輸入,在表單屬性之外的如何快速校驗呢?我們一起來看看吧!
  • 每日一問:LayoutParams 你知道多少?
    而且大多數人對此都是司空見慣,我們 XML 文件裡面的每一個 View 都會接觸到 layout_xxx 這樣的屬性,這實際上就是對布局參數的描述。大概大家也就清楚了,layout_ 這樣開頭的東西都不屬於 View,而是控制具體顯示在哪裡。
  • 解決CoordinatorLayout的動畫抖動以及回彈問題
    ://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <android.support.design.widget.AppBarLayout
  • Design is respect-InteriorDesign中文版10周年系列展覽
    designboom設計邦中國↑↑↑接收每天原汁原味的設計
  • 微信小程序開發實戰(9):單行輸入和多行輸入組件
    下面是input屬性的屬性及其含義。value:String類型,輸入框的當前內容type:String類型,默認值是text。可指定的值:text, number, idcard, digitpassword:Boolean類型,默認值是false,是否以密碼形式錄入文本(所有的文本字符都顯示為點)placeholder:String類型,輸入框為空時顯示的文本placeholder-style:String類型,指定 placeholder 的樣式placeholder-class
  • Sika·Design | 敬畏生命,敬重自然,我們才會走得長遠
    「 When I started in the furniture business many years ago, I wasintrigued by the rattan material’s designpossibilities.
  • input file文件上傳與批量上傳
    ### 文件上傳- 利用 input 標籤設置 type="file" 打開本地的資源管理器;- input 標籤的 accept 屬性可以設置上傳什麼類型的文件;accept 屬性並不會驗證選中文件的類型.
  • 2016年GOOD DESIGN AWARD設計師交流盛會上海站即將在漫生快活舉辦
    Thedesign ofPRIMUS 200 epitomizes the product values and commitment tothecustomers:Simplicity, Ease of Use, and Quality.
  • Android開發Fragment
    本文介紹如何在開發應用時使用片段,包括如何在將片段添加到 Activity 返回棧時保持其狀態、如何與 Activity 及 Activity 中的其他片段共享事件、如何為 Activity 的應用欄發揮作用等等。
  • 新版MATERIAL DESIGN 官方動效指南
    在Material design的世界中,動效用一種優雅、流動的方式來描述空間關係、功能、和意向。動效可以向我們展示一個App 是如何構成和用途。動效可以做到:不同視圖之間的焦點引導。翻譯 | 平行煎餅互 聯 網 用 戶 體 驗 專 家adinnet_design長按二維碼關注回復關鍵詞查閱更多:用戶體驗 UE UX UI 設計 視覺 配色 排版 移動端 web app 響應式 交互 動效 GIF 創意 網頁 產品 H5 艾藝
  • Layout artist-藏在鏡頭後面的攝影師
    入行第一份職位便是layout師。參與過《魁拔》《大聖歸來》《龍在哪裡》等動畫長片的製作。擔任過layout師,動畫師,綁定師,動畫導演等職位。現在在追光動畫擔任layout lead,完成了《小門神》的layout製作。
  • 《不要餵食猴子》怎麼打通作者電話 打不通作者電話原因詳解
    311px;height:60px;float:right;} .t2c_r_t{width:311px;height:29px;background-position:-183px -18px;margin-top:4px;background-image: url(//www.ali213.net/news/images/news_show_ui.png);} .t2c_r_t .soinput