相关文章推荐

项目需求, 密码框中的密码可以按小眼睛进行显示与隐藏, 密码框提示语在点击时有交互动效, 并且密码长度不符合要求时需要有提示语. 因为普通的 EditText 做起来比较复杂, 所以选型为 TextInputLayout + TextInputEditText 组合来完成

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical"
    tools:context=".TextInputLayoutActivity">
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til"
        android:layout_width="match_parent"
        android:background="@color/white"
        app:errorEnabled="true"
        app:errorTextColor="#FF0000"
        app:hintTextColor="@color/black"
        app:errorTextAppearance="@style/error"
        android:layout_height="wrap_content">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/et_email"
            app:errorEnabled="true"
            android:background="@color/white"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入密码"
            android:textColor="@color/black"
            android:imeOptions="actionNext"
            android:drawablePadding="8dp"
            android:drawableStart="@mipmap/ic_password"
            android:maxLength="128"
            android:maxLines="1"
            android:singleLine="true"
            android:textColorHint="#B6B6B6" />
    </com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

app:errorEnabled指定是否可显示报错信息
app:errorTextColor指定报错文字颜色
app:hintTextColor指定hint文字的颜色
app:passwordToggleDrawable自定义小眼睛

app:passwordToggleDrawable="@drawable/pass_word_select"

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/password_show" android:state_checked="true" />
    <item android:drawable="@drawable/password_hide" />
</selector>

设置小眼睛

TextInputLayout.END_ICON_PASSWORD_TOGGLE显示密码切换小眼睛
TextInputLayout.END_ICON_CLEAR_TEXT 显示清空密码按钮
TextInputLayout.END_ICON_CUSTOM 显示自定义图标
TextInputLayout.END_ICON_NONE 默认不显示

TextInputLayout textInputLayout = findViewById(R.id.til);
textInputLayout.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
textInputLayout.setError("密码不能小于6位");
这个提示满足需要, 但是多了一个小图标, 如果要去除可以使用以下代码

textInputLayout.setErrorIconDrawable(0);

也可以通过setErrorIconDrawable方法进行自定义报错图标
如果需要取消报错

textInputLayout.setError("");
复制代码
    • 1.8w
  • 私信
     
    推荐文章