日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

TextInputLayout-Android M新控件

發布時間:2025/3/21 Android 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TextInputLayout-Android M新控件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Introduction

同樣的,這個控件也是Material Design中的控件。

Google I/O 2015 ,谷歌意識到向后兼容是實現material design的重要部分。當然support library,比如appcompat-v4 和 appcompat-v7是解決方案的一部分。

但是Theme.AppCompat 并沒有實現谷歌官方應用中用到的每個material組建。其中一個重要的特性就是AppCompat theme沒有提供一個顯示在EditText上方的浮動標簽。

比如下圖所示:

在Google I/O 2015期間,安卓團隊發布了一個嶄新的兼容庫,Design Support Library。它簡直就是為解決這個問題而生的。本博文將演示如何使用Design Support Library中的TextInputLayout控件。


官方API


運行效果


Implementing TextInputLayout

Import the Support Libraries

要使用TextInputLayout控件,你需要導入兩個Library。第一個是appcompat-v7,它確保material style可以向后兼容。第二個是Design Support Library。

我在寫這邊博客的時候,support已經更新到23.2.0了,不過還是用我個人常用的23.1.1吧。雖然這個控件是在22.2.0中推出的,記得所有的Support library的版本保持一致。

在你的build.gradle文件中,添加如下依賴:

compile 'com.android.support:appcompat-v7:23.1.1'compile 'com.android.support:design:23.1.1'

如果Gradle沒有自動詢問同步項目,選擇build菜單中的Make module ‘app’ ,或者按Ctrl +F9。這樣Android Studio 編譯系統會自動獲取必要的資源,然后你就能夠使用需要的類了。

Design the User Interface

這個用戶界面非常簡單。它顯示了一個“登錄”文字與兩個EditText元素,一個是為用戶名準備的,一個是為密碼準備的。布局中還包含了一個觸發登陸流程的按鈕。背景顏色是扁平風格的灰色。

另一個重要的細節是記得正確設置EditText的inputType屬性。
第一個EditText的inputType應該設置成textEmail,
而第二個應該設置成textPassword。

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:background="#e3e3e3"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="@dimen/activity_horizontal_margin"tools:context=".LoginActivity"android:orientation="vertical"><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.5"android:orientation="vertical"><TextView android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_centerInParent="true"android:gravity="center"android:text="Welcome"android:textSize="30sp"android:textColor="#333333"/></RelativeLayout><LinearLayout android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.5"android:orientation="vertical"><EditText android:id="@+id/username"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textEmailAddress"/><EditText android:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"/><Button android:id="@+id/btn"android:layout_marginTop="4dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Login"/></LinearLayout></LinearLayout>

你可能還想去掉app bar,也就是過去說的actionbar,編輯style.xml文件:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> </style>

或者在代碼中設置
因為繼承的是AppCompatActivity

supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

Using TextInputLayout

TextInputLayout控件和LinearLayout完全一樣,它只是一個容器。跟ScrollView一樣,TextInputLayout只接受一個子元素。子元素需要是一個EditText元素。

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

注意這里我在EditText中指定了另一個參數,hint。就如你知道的,這個屬性允許你在EditText的內容為空的時候顯示一個自定義的提示。一旦用戶開始輸入,hint會消失。這并不理想,因為用戶丟失了他們輸入信息的上下文提示。

有了TextInputLayout,這將不再是問題。一個單一的EditText 在輸入文字的時候會隱藏hint,而被包含在TextInputLayout中的EditText則會讓hint變成一個在EditText上方的浮動標簽。同時還包括一個漂亮的material動畫。

接下來,我們對password輸入框做同樣的事情。

<android.support.design.widget.TextInputLayoutandroid:id="@+id/passwordWrapper"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@id/usernameWrapper"android:layout_marginTop="4dp"><EditTextandroid:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"android:hint="Password"/></android.support.design.widget.TextInputLayout>

官方的教程說,EditText的hint會表現的跟預期一致。但是沒有material動畫也沒有浮動標簽,需要設置hint, 但是經驗證,不設置,只要在xml中設置了 android:hint也是可以達到效果的。

官方使用的compile 'com.android.support:design:22.2.0'
我的工程使用的是compile 'com.android.support:design:23.1.1'

未做驗證~

Setting Hints

初始化對theTextInputLayout視圖的引用

usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);

設置一個hint,使用setHint方法:

usernameWrapper.setHint("Username"); passwordWrapper.setHint("Password");

至此,你的登陸界面現在很好的遵循了material設計規范。運行項目查看你的登陸界面。


Handling Errors

TextInputLayout的另一個特色是它可以處理錯誤。通過驗證輸入,你可以防止用戶輸入無效的郵箱地址或者是太短的密碼。如果沒有驗證,后臺可能反饋回不正確的結果呈現給用戶。對于用戶來說既浪費了時間又體驗不好。在發送到后臺之前你應該先檢查輸入的正確性。

Implementing the onClick Method

首先你需要處理按鈕的點擊。有許多方法處理按鈕的點擊。其中一種就是寫一個自定義的方法然后在xml中通過onClick屬性指定,我喜歡setOnClickListener的方式,但這只是個人喜好。

btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// STUB} });

我們知道當這個方法調用之后,用戶不再需要鍵盤。不幸的是,如果你不告訴它,安卓不會自動的隱藏虛擬鍵盤。在onClick方法體中調用hideKeyboard。

private void hideKeyboard() {View view = getCurrentFocus();if (view != null) {((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);} }

Validating Input

在設置錯誤標簽之前,我們需要定義什么是錯誤,什么不是。我們假設用戶名必須是一個郵箱地址并且我們想阻止用戶輸入無效的郵箱地址。

驗證郵箱地址有點復雜。我們必須依賴正則表達式。如果你想也可以使用Apache Commons library。

我使用了Wikipedia 上關于郵箱驗證的指導,寫了如下的正則表達式。

/^[a-zA-Z0-9#_~!$&'()*+,;=:."(),:;<>@\[\]\\]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/

因為我們想驗證字符串,我必須依賴Pattern和Matcher兩個類。includeava.util.regex 包。實現如下的方法:

private static final String EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"(),:;<>@\\[\\]\\\\]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$"; private Pattern pattern = Pattern.compile(EMAIL_PATTERN); private Matcher matcher;public boolean validateEmail(String email) {matcher = pattern.matcher(email);return matcher.matches(); }

密碼的驗證簡單的多。很多組織為密碼的驗證采用了不同的策略,但是所有人都會限制最短長度。合理的密碼應該不低于6個字符。

public boolean validatePassword(String password) {return password.length() > 5; }

Retrieving Data 獲取數據

就如我說的,TextInputLayout只是一個容器,但是和LinearLayout和ScrollView不同,你可以使用一個特殊的方法獲得子元素,getEditText,不需要使用findViewById。

public void onClick(View v) {hideKeyboard();String username = usernameWrapper.getEditText().getText().toString();String password = passwordWrapper.getEditText().getText().toString();// TODO: Checks// TODO: Login }

Showing Errors

TextInputLayout的錯誤處理簡單快速。需要的方法是setErrorEnabled和setError。

setError設置一個紅色的錯誤消息,顯示在EditText的下面。如果傳入的參數為null,錯誤消息將清空。并且它會改變整個EditText控件為紅色。

setErrorEnabled開啟錯誤提醒功能。這直接影響到布局的大小,增加底部padding為錯誤標簽讓出空間。在setError設置錯誤消息之前開啟這個功能意味著在顯示錯誤的時候布局不會變化。你可以把這兩個方法結合起來驗證下我所說的。

另一個有趣的事實是如果錯誤功能未開啟但是你調用了傳入非null參數的setError,那么setErrorEnabled(true)將自動被調用。

現在我們定義了什么是錯誤的什么是正確的,也知道了如何獲取EditText中的數據以及顯示可能的錯誤,onClick方法的實現就很簡單了。

public void onClick(View v) {hideKeyboard();String username = usernameWrapper.getEditText().getText().toString();String password = passwordWrapper.getEditText().getText().toString();if (!validateEmail(username)) {usernameWrapper.setError("Not a valid email address!");} else if (!validatePassword(password)) {passwordWrapper.setError("Not a valid password!");} else {usernameWrapper.setErrorEnabled(false);passwordWrapper.setErrorEnabled(false);doLogin();} }

我添加了一個doLogin方法,模擬登錄成功

public void doLogin() {Toast.makeText(getApplicationContext(), "OK! I'm performing login.", Toast.LENGTH_SHORT).show();// TODO: login procedure; not within the scope of this tutorial. }

Styling

你可能還想做最后一件事,改變TextInputLayout控件的顏色。默認AppCompact會把它設置成綠色的,但是很有可能這個顏色會和你的顏色主題(color palette)沖突。

谷歌把Design Support Library寫的很好。每一個控件的顏色都是直接通過主題顏色繪制的,在 style.xml 中指定。打開它添加colorAccent 到主題以改變表單的顏色。

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"><item name="colorAccent">#3498db</item> </style>

Conclusion

我們看到了如何實現新的布局元素TextInputLayout,多虧有了剛剛引入的Design Support Library。

設計范例中,控件的實現需要讓用戶在輸入的過程中不會丟失上下文信息,它是在去年跟Material Design一起被谷歌介紹的。在這之前,沒有讓開發者將這個控件應用到實際項目中的支持庫。現在,如果你的應用有類似數據輸入的地方,你終于可以完全遵循material design 了。


英文原文請訪問:
creating-a-login-screen-using-textinputlayout

總結

以上是生活随笔為你收集整理的TextInputLayout-Android M新控件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。