Android使用TextInputLayout創(chuàng)建登陸頁(yè)面
本教程中,我將再次討論Material Design。Google I/O 2015 對(duì)于每一個(gè)開(kāi)發(fā)者來(lái)說(shuō)都是一個(gè)重大的事件,設(shè)計(jì)當(dāng)然也是談資之一。
谷歌意識(shí)到向后兼容是實(shí)現(xiàn)material design的重要部分。當(dāng)然support library,比如appcompat-v4 和 appcompat-v7是解決方案的一部分。
但是Theme.AppCompat 并沒(méi)有實(shí)現(xiàn)谷歌官方應(yīng)用中用到的每個(gè)material組建。其中一個(gè)重要的特性就是AppCompat theme沒(méi)有提供一個(gè)顯示在EditText上方的浮動(dòng)標(biāo)簽。你可以從下方的途中知曉我說(shuō)的是什么。
在Google I/O 2015期間,安卓團(tuán)隊(duì)發(fā)布了一個(gè)嶄新的兼容庫(kù),Design Support Library。它簡(jiǎn)直就是為解決這個(gè)問(wèn)題而生的。本教程將演示如何使用Design Support Library中的TextInputLayout控件。
1. 實(shí)現(xiàn) TextInputLayout
第一步: 創(chuàng)建一個(gè)新的項(xiàng)目
在Android Studio中 選擇New > New project 。填入所需的信息然后創(chuàng)建項(xiàng)目。我的例子的target api是17,這是Design Support Library支持的最小api版本。這個(gè)級(jí)別的api基本上已經(jīng)支持絕大多數(shù)設(shè)備了。我把主activity命名為L(zhǎng)oginActivity,它的布局文件命名為activity_login.xml。
創(chuàng)建完項(xiàng)目之后,在主activity中把Android Studio自動(dòng)產(chǎn)生的onCreateOptionsMenu 和onOptionsItemSelected方法刪掉。我們要?jiǎng)?chuàng)建的登陸界面不需要菜單所以刪掉這些方法是ok的。記得也刪掉res/menu目錄中的XML 菜單文件。
第二步:導(dǎo)入Support Library
要使用TextInputLayout控件,你需要導(dǎo)入兩個(gè)Library。第一個(gè)是appcompat-v7,它確保material style可以向后兼容。第二個(gè)是Design Support Library。在你的build.gradle文件中,添加如下依賴:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:design:22.2.0' compile 'com.android.support:appcompat-v7:22.2.0' }
如果Gradle沒(méi)有自動(dòng)詢問(wèn)同步項(xiàng)目,選擇build菜單中的Make module ‘a(chǎn)pp' ,或者按F9。這樣Android Studio 編譯系統(tǒng)會(huì)自動(dòng)獲取必要的資源,然后你就能夠使用需要的類了。
第三步:設(shè)計(jì)用戶界面
這個(gè)項(xiàng)目的用戶界面非常簡(jiǎn)單。它顯示了一個(gè)“歡迎”文字(可以很容易替換成logo什么的)與兩個(gè)EditText元素,一個(gè)是為用戶名準(zhǔn)備的,一個(gè)是為密碼準(zhǔn)備的。布局中還包含了一個(gè)觸發(fā)登陸流程的按鈕。背景顏色是扁平風(fēng)格的灰色。
另一個(gè)重要的細(xì)節(jié)是記得正確設(shè)置EditText的inputType屬性。第一個(gè)EditText的inputType應(yīng)該設(shè)置成textEmail,而第二個(gè)應(yīng)該設(shè)置成textPassword。下面是布局的樣子:
<LinearLayout xmlns: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,也就是過(guò)去說(shuō)的actionbar,編輯style.xml文件:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> </style>
第四步: 使用TextInputLayout
我們總算到了本教程最有趣的部分。TextInputLayout控件和LinearLayout完全一樣,它只是一個(gè)容器。跟ScrollView一樣,TextInputLayout只接受一個(gè)子元素。子元素需要是一個(gè)EditText元素。
<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:inputType="textEmailAddress" android:hint="Username"/> </android.support.design.widget.TextInputLayout>
注意這里我在EditText中指定了另一個(gè)參數(shù),hint。就如你知道的,這個(gè)屬性允許你在EditText的內(nèi)容為空的時(shí)候顯示一個(gè)自定義的提示。一旦用戶開(kāi)始輸入,hint會(huì)消失。這并不理想,因?yàn)橛脩魜G失了他們輸入信息的上下文提示。
有了TextInputLayout,這將不再是問(wèn)題。一個(gè)單一的EditText 在輸入文字的時(shí)候會(huì)隱藏hint,而被包含在TextInputLayout中的EditText則會(huì)讓hint變成一個(gè)在EditText上方的浮動(dòng)標(biāo)簽。同時(shí)還包括一個(gè)漂亮的material動(dòng)畫。
接下來(lái),我們對(duì)password輸入框做同樣的事情。
<android.support.design.widget.TextInputLayout android:id="@+id/passwordWrapper" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/usernameWrapper" android:layout_marginTop="4dp"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="Password"/> </android.support.design.widget.TextInputLayout>
現(xiàn)在如果你運(yùn)行應(yīng)用,什么也不會(huì)發(fā)生。當(dāng)然,EditText的hint會(huì)表現(xiàn)的跟預(yù)期一致。但是沒(méi)有material動(dòng)畫也沒(méi)有浮動(dòng)標(biāo)簽。為什么會(huì)這樣?我們還缺少一些代碼。
第五步: 設(shè)置 Hints
下面是setContentView方法,初始化對(duì)theTextInputLayout視圖的引用。
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper); final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
要讓浮動(dòng)標(biāo)簽動(dòng)起來(lái),你只需設(shè)置一個(gè)hint,使用setHint方法:
usernameWrapper.setHint("Username"); passwordWrapper.setHint("Password");
然后你就完成了。你的登陸界面現(xiàn)在很好的遵循了material設(shè)計(jì)規(guī)范。運(yùn)行項(xiàng)目查看你的登陸界面。
2. 處理錯(cuò)誤
TextInputLayout的另一個(gè)特色是它可以處理錯(cuò)誤。通過(guò)驗(yàn)證輸入,你可以防止用戶輸入無(wú)效的郵箱地址或者是太短的密碼。如果沒(méi)有驗(yàn)證,后臺(tái)可能反饋回不正確的結(jié)果呈現(xiàn)給用戶。對(duì)于用戶來(lái)說(shuō)既浪費(fèi)了時(shí)間又體驗(yàn)不好。在發(fā)送到后臺(tái)之前你應(yīng)該先檢查輸入的正確性。
第一步: 實(shí)現(xiàn) onClick 方法
首先你需要處理按鈕的點(diǎn)擊。有許多方法處理按鈕的點(diǎn)擊。其中一種就是寫一個(gè)自定義的方法然后在xml中通過(guò)onClick屬性指定,我喜歡setOnClickListener的方式,但這只是個(gè)人喜好。
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // STUB } });
我們知道當(dāng)這個(gè)方法調(diào)用之后,用戶不再需要鍵盤。不幸的是,如果你不告訴它,安卓不會(huì)自動(dòng)的隱藏虛擬鍵盤。在onClick方法體中調(diào)用hideKeyboard。
private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)). hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }
第二步: 輸入驗(yàn)證
在設(shè)置錯(cuò)誤標(biāo)簽之前,我們需要定義什么是錯(cuò)誤,什么不是。我們假設(shè)用戶名必須是一個(gè)郵箱地址并且我們想阻止用戶輸入無(wú)效的郵箱地址。
驗(yàn)證郵箱地址有點(diǎn)復(fù)雜。我們必須依賴正則表達(dá)式。如果你想也可以使用Apache Commons library。
我使用了Wikipedia 上關(guān)于郵箱驗(yàn)證的指導(dǎo),寫了如下的正則表達(dá)式。
/^[a-zA-Z0-9#_~!$&'()*+,;=:."(),:;<>@\[\]\\]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/
注:這個(gè)正則表達(dá)式的意思我就不翻譯了,如果你不熟悉正則表達(dá)式看了也沒(méi)啥用。
因?yàn)槲覀兿腧?yàn)證字符串,我必須依賴Pattern和Matcher兩個(gè)類。includeava.util.regex 包。實(shí)現(xiàn)如下的方法:
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(); }
密碼的驗(yàn)證簡(jiǎn)單的多。很多組織為密碼的驗(yàn)證采用了不同的策略,但是所有人都會(huì)限制最短長(zhǎng)度。合理的密碼應(yīng)該不低于6個(gè)字符。
public boolean validatePassword(String password) { return password.length() > 5; }
第三步: 獲取數(shù)據(jù)
就如我說(shuō)的,TextInputLayout只是一個(gè)容器,但是和LinearLayout和ScrollView不同,你可以使用一個(gè)特殊的方法獲得子元素,getEditText,不需要使用findViewById。
public void onClick(View v) { hideKeyboard(); String username = usernameWrapper.getEditText().getText().toString(); String password = passwordWrapper.getEditText().getText().toString(); // TODO: Checks // TODO: Login }
第四步: 顯示錯(cuò)誤
TextInputLayout的錯(cuò)誤處理簡(jiǎn)單快速。需要的方法是setErrorEnabled和setError。
setError設(shè)置一個(gè)紅色的錯(cuò)誤消息,顯示在EditText的下面。如果傳入的參數(shù)為null,錯(cuò)誤消息將清空。并且它會(huì)改變整個(gè)EditText控件為紅色。
setErrorEnabled開(kāi)啟錯(cuò)誤提醒功能。這直接影響到布局的大小,增加底部padding為錯(cuò)誤標(biāo)簽讓出空間。在setError設(shè)置錯(cuò)誤消息之前開(kāi)啟這個(gè)功能意味著在顯示錯(cuò)誤的時(shí)候布局不會(huì)變化。你可以把這兩個(gè)方法結(jié)合起來(lái)驗(yàn)證下我所說(shuō)的。
另一個(gè)有趣的事實(shí)是如果錯(cuò)誤功能未開(kāi)啟但是你調(diào)用了傳入非null參數(shù)的setError,那么setErrorEnabled(true)將自動(dòng)被調(diào)用。
現(xiàn)在我們定義了什么是錯(cuò)誤的什么是正確的,也知道了如何獲取EditText中的數(shù)據(jù)以及顯示可能的錯(cuò)誤,onClick方法的實(shí)現(xiàn)就很簡(jiǎn)單了。
public void onClick(View v) { hideKeyboard(); String username = usernameWrapper.getEditText().getText().toString(); String password = usernameWrapper.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(); } }
我添加了一個(gè)doLogin方法,但是目前它是空的因?yàn)檫@超出了本教程的范圍。
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. }
3. 樣式
你可能還想做最后一件事,改變TextInputLayout控件的顏色。默認(rèn)AppCompact會(huì)把它設(shè)置成綠色的,但是很有可能這個(gè)顏色會(huì)和你的顏色主題(color palette)沖突。
谷歌把Design Support Library寫的很好。每一個(gè)控件的顏色都是直接通過(guò)主題顏色繪制的,在 style.xml 中指定。打開(kāi)它添加colorAccent 到主題以改變表單的顏色。
<style name="AppTheme" parent="Theme.A <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorAccent">#3498db</item> </style>
總結(jié)
本教程中,我們看到了如何實(shí)現(xiàn)新的布局元素TextInputLayout,多虧有了剛剛引入的Design Support Library。
設(shè)計(jì)范例中,控件的實(shí)現(xiàn)需要讓用戶在輸入的過(guò)程中不會(huì)丟失上下文信息,它是在去年跟Material Design一起被谷歌介紹的。在這之前,沒(méi)有讓開(kāi)發(fā)者將這個(gè)控件應(yīng)用到實(shí)際項(xiàng)目中的支持庫(kù)。現(xiàn)在,如果你的應(yīng)用有類似數(shù)據(jù)輸入的地方,你終于可以完全遵循material design 了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Handler實(shí)現(xiàn)線程之間的通信下載文件動(dòng)態(tài)更新進(jìn)度條
每一個(gè)線程對(duì)應(yīng)一個(gè)消息隊(duì)列MessageQueue,實(shí)現(xiàn)線程之間的通信,可通過(guò)Handler對(duì)象將數(shù)據(jù)裝進(jìn)Message中,再將消息加入消息隊(duì)列,而后線程會(huì)依次處理消息隊(duì)列中的消息。這篇文章主要介紹了Handler實(shí)現(xiàn)線程之間的通信下載文件動(dòng)態(tài)更新進(jìn)度條,需要的朋友可以參考下2017-08-08Android實(shí)現(xiàn)帶圖標(biāo)的列表對(duì)話框
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)帶圖標(biāo)的列表對(duì)話框,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12Android中ViewPager帶來(lái)的滑動(dòng)卡頓問(wèn)題解決要點(diǎn)解析
這里我們主要針對(duì)ViewGroup的SwipeRefreshLayout中引入ViewPager所引起的滑動(dòng)沖突問(wèn)題進(jìn)行討論,一起來(lái)看一下Android中ViewPager帶來(lái)的滑動(dòng)卡頓問(wèn)題解決要點(diǎn)解析:2016-06-06Android如何獲取屏幕、狀態(tài)欄及標(biāo)題欄的高度詳解
在日常開(kāi)發(fā)中,經(jīng)常會(huì)遇到獲取屏幕高度、狀態(tài)欄高度等需求,所以下面這篇文章就給大家總結(jié)介紹了關(guān)于Android如何獲取屏幕、狀態(tài)欄及標(biāo)題欄高度的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們可以參考下。2017-10-10Android編程實(shí)現(xiàn)自定義Tab選項(xiàng)卡功能示例
這篇文章主要介紹了Android編程實(shí)現(xiàn)自定義Tab選項(xiàng)卡功能,結(jié)合完整實(shí)例形式分析了Android自定義tab選項(xiàng)卡的遍歷、設(shè)置及屬性操作相關(guān)技巧,需要的朋友可以參考下2017-02-02深入Android Handler,MessageQueue與Looper關(guān)系
這篇文章主要介紹了深入Android Handler,MessageQueue與Looper關(guān)系,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08