Android之自定义EditText光标和下划线颜色

最近在写些小Demo复习基础,在用到EditText的时候突然发现之前几乎没有注意到它的光标和下划线的颜色,于是花了不少时间,看了不少博客,现在就来总结和分享一下收获。

1、第一印象:原生的EditText

我们要在原生的EditText上修改,首先当然要认识一下它的本来面目。在Android Studio中新建一个工程,让MainActivity继承于AppCompatActivity(为什么要这样做,后面再说),然后在MainActivity的布局中放置一个EditText:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lindroid.edittext.MainActivity">

    <EditText
        android:hint="原生的EditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

运行工程,仔细观察可以看到光标和下划线都是粉红色的。现在就让我们循序渐进,先修改它的光标颜色。
这里写图片描述

2、自定义光标颜色

EditText 有一个属性:android:textCursorDrawable ,它就是用来设置光标样式的。为了加深认识,大家先额外做个小实验:将textCursorDrawable设置为@null,表示去除系统默认的样式,但我们都记得隐藏光标的属性是android:cursorVisible , 那么这时光标会是什么样子的呢?你可以给文字(android:textColor)和提示文字(android:textColorHint属性)设置不同的颜色,运行之后就会发现此时光标的颜色是跟文字的保持一致的。

了解了android:textCursorDrawable 的作用之后,我们可以在drawable资源文件夹下新建一个cursor_color.xml文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:width="2dp" />
    <solid android:color="@android:color/holo_blue_light" />
</shape>

光标的颜色为系统自带的浅蓝色,宽度为2dp。在原生的EditText下面放置一个新的EditText:

    <EditText
        android:textCursorDrawable="@drawable/cursor_color"
        android:hint="自定义光标颜色"
        android:layout_width=
  • 21
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值