title: EditText 基本用法
tags: EditText,编辑框,输入框
---
EditText介绍:
EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是用户跟Android应用进行数据传输的窗户,比如实现一个登陆界面,需要用户输入账号密码,然后我们获取用户输入的内容,提交给服务器进行判断。
EditText 支持的 XML 属性及相关方法
android:text |
setText(CharSequence text) |
设置文本内容 |
android:textColor |
setTextColor(int color) |
字体颜色 |
android:hint |
setHint(int resid) |
内容为空时候显示的文本 |
android:textColorHint |
void setHintTextColor(int color) |
为空时显示的文本的颜色 |
android:inputType |
setInputType(int type) |
限制输入类型 number:整数类型 numberDecimal:小数点类型 date:日期类型 text:文本类型(默认值) phone:拨号键盘 textPassword:密码 textVisiblePassword:可见密码 textUri:网址 |
android:maxLength |
|
限制显示的文本长度,超出部分不显示 |
android:minLines |
setMaxLines(int maxlines) |
设置文本的最小行数 |
android:gravity |
setGravity(int gravity) |
设置文本位置,如设置成“center”,文本将居中显示。 |
android:drawableLeft |
setCompoundDrawables(Drawable left,Drawable top,Drawable right, Drawable bottom) |
在text的左边输出一个drawable,如图片 |
android:drawablePadding |
|
设置text与drawable(图片)的间隔,与drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可设置为负数,单独使用没有效果。 |
android:digits |
|
设置允许输入哪些字符。如“1234567890” |
android:ellipsize |
|
设置当文字过长时,该控件该如何显示。 start:省略号显示在开头 end:省略号显示在结尾 middle:省略号显示在中间 marquee:以跑马灯的方式显示(动画横向移动) |
android:lines |
setLines(int lines) |
设置文本的行数,设置两行就显示两行,即使第二行没有数据。 |
android:lineSpacingExtra |
|
设置行间距 |
android:singleLine |
setSingleLine() |
true:单行显示 false:可以多行 |
android:textStyle |
|
设置字形,可以设置一个或多个,用"|"隔开 bold:粗体 italic:斜体 bolditalic:又粗又斜 |
EditText实例:开发中常用的登录界面
首先我们来看布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@null"
android:inputType="number"
android:maxLength="11"
android:hint="请输入手机号"
android:drawablePadding="10dp"
android:padding="10dp"
android:drawableLeft="@mipmap/icon_phone"
android:drawableBottom="@drawable/shape_et_bottom_line"
android:layout_marginTop="20dp"/>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:background="@null"
android:inputType="textPassword"
android:maxLength="16"
android:padding="10dp"
android:drawablePadding="10dp"
android:hint="请输入密码"
android:drawableBottom="@drawable/shape_et_bottom_line"
android:drawableLeft="@mipmap/icon_password"/>
<TextView
android:id="@+id/tv_login"