原鏈接http://www.cnblogs.com/yishaochu/p/5785234.html
title: EditText 基本用法
tags: EditText,編輯框,輸入框
---
EditText介紹:
EditText 在開發(fā)中也是經(jīng)常用到的控件,也是一個比較必要的組件,可以說它是用戶跟Android應用進行數(shù)據(jù)傳輸?shù)拇皯?,比如實現(xiàn)一個登陸界面,需要用戶輸入賬號密碼,然后我們獲取用戶輸入的內(nèi)容,提交給服務器進行判斷。
EditText 支持的 XML 屬性及相關方法
XML 屬性相關方法說明
android:textsetText(CharSequence text)設置文本內(nèi)容
android:textColorsetTextColor(int color)字體顏色
android:hintsetHint(int resid)內(nèi)容為空時候顯示的文本
android:textColorHintvoid setHintTextColor(int color)為空時顯示的文本的顏色
android:inputTypesetInputType(int type)限制輸入類型
number:整數(shù)類型
numberDecimal:小數(shù)點類型
date:日期類型
text:文本類型(默認值)
phone:撥號鍵盤
textPassword:密碼
textVisiblePassword:可見密碼
textUri:網(wǎng)址
android:maxLength限制顯示的文本長度,超出部分不顯示
android:minLinessetMaxLines(int maxlines)設置文本的最小行數(shù)
android:gravitysetGravity(int gravity)設置文本位置,如設置成“center”,文本將居中顯示。
android:drawableLeftsetCompoundDrawables(Drawable left,Drawable top,Drawable right, Drawable bottom)在text的左邊輸出一個drawable,如圖片
android:drawablePadding設置text與drawable(圖片)的間隔,與drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可設置為負數(shù),單獨使用沒有效果。
android:digits設置允許輸入哪些字符。如“1234567890”
android:ellipsize設置當文字過長時,該控件該如何顯示。
start:省略號顯示在開頭
end:省略號顯示在結(jié)尾
middle:省略號顯示在中間
marquee:以跑馬燈的方式顯示(動畫橫向移動)
android:linessetLines(int lines)設置文本的行數(shù),設置兩行就顯示兩行,即使第二行沒有數(shù)據(jù)。
android:lineSpacingExtra設置行間距
android:singleLinesetSingleLine()true:單行顯示 false:可以多行
android:textStyle設置字形,可以設置一個或多個,用"\
EditText實例:開發(fā)中常用的登錄界面
首先我們來看布局文件:activity_main.xml
運行效果圖如下:
這兩個輸入框的用的的大部分屬性都在上面的表格中了,我這里解決下沒有說過的屬性。
android:background="@null" 輸入框無背景
android:drawableBottom="@drawable/shape_et_bottom_line" 底部引入一個shape布局文件,這個布局文件就是輸入框的下劃線。
shape_et_bottom_line.xml內(nèi)容如下:
EditeText還有哪些功能?
1.監(jiān)聽用戶輸入的內(nèi)容.
有這樣一個場景,一個搜索框,只要用戶輸入了內(nèi)容就去請求服務器,于是我們在Activity里面監(jiān)聽EditeText文本改變事件。
EditText etOne= (EditText) findViewById(R.id.et_phone);etOne.addTextChangedListener(newTextWatcher() {@OverridepublicvoidbeforeTextChanged(CharSequence s,intstart,intcount,intafter){? ? ? ? ? ? ? ? Log.i("Ansen","內(nèi)容改變之前調(diào)用:"+s);? ? ? ? ? ? }@OverridepublicvoidonTextChanged(CharSequence s,intstart,intbefore,intcount){? ? ? ? ? ? ? ? Log.i("Ansen","內(nèi)容改變,可以去告訴服務器:"+s);? ? ? ? ? ? }@OverridepublicvoidafterTextChanged(Editable s){? ? ? ? ? ? ? ? Log.i("Ansen","內(nèi)容改變之后調(diào)用:"+s);? ? ? ? ? ? } });
首先我們通過id找到EditText控件,并且添加監(jiān)聽函數(shù),內(nèi)部內(nèi)實現(xiàn)TextWatcher接口,重寫三個方法。我們可以在onTextChanged方法中告訴服務器我要搜索的內(nèi)容。
源碼下載
點擊下載源碼https://github.com/ansen666/EditTextDemo
各位看官如果覺得文章不錯,幫忙點個贊吧,對于你來說是舉手之勞,但對于我來說這就是堅持下去的動力。
如果你想第一時間看我們的后期文章,掃碼關注公眾號,每周不定期推送Android開發(fā)實戰(zhàn)教程文章,你還等什么,趕快關注吧,學好技術(shù),出任ceo,贏取白富美。。。。