安卓进阶

EditText 自定义选中字体、光标和水滴样式

2022-01-19  本文已影响0人  飞往卓越之路

开发中可能需要灵活自定义EditText的光标、长按选中的文字和水滴样式,怎么做呢?

  <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@android:color/holo_blue_light</item>
    </style>  

效果展示:


全局修改.jpg
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#cc0000"/>
    <size android:width="2dp" />
</shape>

EditText控件中增加android:textCursorDrawable="@drawable/shape_edit_cursor":

<EditText
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:textCursorDrawable="@drawable/shape_edit_cursor"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
效果展示: Dialog中的EditText光标.png

(2)修改长按字体的选中颜色和水滴颜色:
在自定义的style里,通过
<item name="android:textColorHighlight">#66cc0000</item>
设置字体选中蒙层的颜色,通过
<item name="android:colorControlActivated">#cc0000</item>
(要求API至少21)设置水滴颜色

<style name="WidgetDialog" parent="@android:style/Theme.Dialog">
        <item name="android:background">#00000000</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:textColorHighlight">#66cc0000</item>
        <item name="android:colorControlActivated">#cc0000</item>
    </style>

然后在dialog里设置该style。

效果展示: Dialog中的EditText选中部分和水滴的颜色.png
上一篇 下一篇

猜你喜欢

热点阅读