Android Material Design 之TextInputLayout TextInputEditText
//google 官方网站 https://material.io/guidelines/components/text-fields.html#text-fields-layout
添加依赖:
compile 'com.android.support:design:24.2.0'
UI组件
<android.support.design.widget.TextInputLayout android:id="@+id/phone1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" app:counterEnabled="true" //设置是否显示字符长度 app:counterMaxLength="11">//设置显示字符长度 <android.support.design.widget.TextInputEditText android:id="@+id/phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_phone" //设置左边显示的图片 android:drawablePadding="10dp" //设置图片的内边距 //使用TextInputLayout
时,设置 EditText 的 drawable //图标时需要同时使用相对值 (start/end) 和 绝对值 (left/right),否则 drawable 存在显示兼容问题。 android:drawableStart="@drawable/ic_phone" android:gravity="center_vertical" android:hint="请输入手机号" android:inputType="number"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/password1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" //当输入框内容为密码类信息时,可以通过passwordToggleEnabled
属性或者 //setPasswordVisibilityToggleEnabled(boolean)
方法在输入框右侧 drawableRight //的位置显示一个切换按钮,控制输入内容的显示与隐藏。 app:passwordToggleEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_password_icon" android:drawablePadding="10dp" android:drawableStart="@drawable/ic_password_icon" android:hint="请输入密码" android:inputType="textPassword"/> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="12dp" android:text="登录"/>
TextInputLayout 还有一个错误提示:
findViewById(R.id.login).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String phoneNumber = phone.getText().toString(); if (!judgePhone(phoneNumber)){ //如果出现错误,则会再下方显示错误提示 phone1.setError("手机输入错误"); phone1.setErrorEnabled(true); } } });