Android 中 TextinputLayout 的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nenguou04/article/details/78875397

TextinputLayout 是 Android 5.0 之后才出现的东西,虽然现在应用的不是特别多,但效果真的很赞!在此记录一下 TextinputLayout 的一些用法

TextinputLayout 例子

Layout which wraps an EditText (or descendant) to show a floating label when the hint is hidden due to the user inputting text.

TextinputLayout 在内部嵌套一个 EditText,并展示一个浮动的标签,标签会在用户输入的时候移动到 EditText 上方。

我在这里简单的记录一下 TextInputLayout 的用法


添加依赖

dependencies{
    compile ‘com.android.support:appcompat-v7:25.0.1’
    compile ‘com.android.support:design:25.0.1'
}

设置相关属性

  • 开启浮动标签
    在 TextinputLayout 中加入 hint 属性
  • 关闭浮动标签
    app:hintEnable=“true | false”
  • 浮动标签动画
    app:hintAnimationEnable=“true | false”
  • 自定义浮动标签
 <style name=“hintAppearence” parent=“TextAppearance.AppCompat”>
     <item name=“android:textSize”>14sp</item>
     <item name=“android:textColor”>#00ff00</item>
 </style>
在 TextinputLayout 中加入 app:hintAppearance=“@style/hintAppearence"
  • 在 EditText 下显示字数统计
    app:counterEnable=“true”
    app:counterMaxLength=“11”. //超过 11 位后换颜色
  • 显示密码:
    app:passwordToggleEnable=“true”
    换图标:app:passwordToggleDrawable=“@mipmap/ic_launcher”
    加颜色:app:passwordToggleTint=“@color/colorBlue”
    设置模式:app:passwordToggleMode=“screen | src_in | src_atop | src_over | multiply”

设置错误提示

setError: 设置错误提示信息
setErrorEnable: 开启错误提示功能
直接调用 setError,会自动调用 setErrorEnable
自定义错误提示样式

<style name=“errorAppearance” parent=“TextAppearance.AppCompat” >
    <item name=“android:textSize”>14sp</item>
    <item name=“android:textColor”>@color/colorBlue</item>
</style>

在 TextinputLayout 中加入自定义的错误提示样式

app:errorTextAppearance=“@style/errorAppearance"

Java 代码实现:

public void onClick(View v){
    String username = usernameTextinputlayout.getEditText().getText().toString();
    String password = passwordTextinputLayout.getEditText().getText().toString();
    If(username == “”){
        usernameTextinputLayout.setError(“用户名不能为空”);
    }else if(password == “”){
        passwordTextinputLayout.setError(“密码不能为空”);
    }else{
        usernameTextinputLayout.setErrorEnable(false);
        passwordTextinputLayout.setErrorEnable(false);
    }
}

修改样式

  • 默认情况下 TextinputLaylout 控件的颜色是 当前 Style 下 colorAccent 设置的,所以修改 style 下 colorAccent 的值即可.
  • 修改光标样式 :
    隐藏光标 : android:cursorVisible.
    光标样式 : android:textCursorDrawable. 为空时,光标颜色和文字颜色一致
    在 drawable 下创建 cursor_color.xml
<shape android:shape=“rectangle">
    <size android:width=“1dp”/>
    <solid android:color=“@color/colorBlue"/>
</shape>

隐藏下划线 : android:background=“@null”

参考:
https://segmentfault.com/a/1190000009507919r

扫描二维码关注公众号,回复: 6115919 查看本文章

欢迎关注我的博客简书CSDNGitHub

猜你喜欢

转载自blog.csdn.net/nenguou04/article/details/78875397