Set EditText cursor color
Asked Answered
C

30

629

I am having this issue where I am using the Android's Holo theme on a tablet project. However, I have a fragment on screen which has a white background. I am adding an EditText component on this fragment. I've tried to override the theme by setting the background of the Holo.Light theme resources. However, my text cursor (carat) remains white and hence, invisible on screen (I can spot it faintly in the edittext field..).

Does anyone know how I can get EditText to use a darker cursor color? I've tried setting the style of the EditText to "@android:style/Widget.Holo.Light.EditText" with no positive result.

Covarrubias answered 30/8, 2011 at 3:43 Comment(1)
Just use inside your TextEditText - android:textCursorDrawable="@color/your_color_choice"Heiduc
R
1363

Setting the android:textCursorDrawable attribute to @null should result in the use of android:textColor as the cursor color.

Attribute "textCursorDrawable" is available in API level 12 and higher

Relict answered 6/2, 2012 at 18:29 Comment(13)
oh man that is SO much more efficient than conjuring up a drawable for the cursor to be black!! I love Android to death but this is such an incredibly bad default behavior... someone really needs to be smacked for it.Autogiro
android 3.2 and above .. sucksDemonstrable
Although if you target >3.2 in your manifest you can use it and it will be ignored for lower versionsDemonstrable
in fact I have just noticed that JellyBean 4.2 does not show the cursor if you use the drawable cursor option ! @null is the way to go!Wiskind
@AidenFry This seems to work for me on 4.2 JB just fine at the themes level.Monomerous
Seems to use the hint color instead if you set it. At least on 4.2. The cursor option has no problems for me from 2.3.3-4.4Skilled
I'm using Android 4.3 on a tablet and it has 2 lines of different color on the sdies of where the blinking should be, that are always visible. Not sure what's up. Looks like it's retaining some of the hint color as a shadow or something.Articulator
That worked OK, but on MEIZU (Android 4.4.2) the cursor became unblinking and grey like frozen or disabled.Antoniettaantonin
When the EditText has android:hint (and android:gravity="center_horizontal"), using (@null) causes the cursor to show up in the wrong place (in the middle of the hint text). Using custom drawable works better.Antilogarithm
This does not work in more recent versions of android. Instead it shows a gray cursor and messes with highlight functionality. Use @star18bit 's answer instead.Amentia
result of android:textColorHint="" as the cursor colorAstronomy
It also changes the text colorPixilated
well, it makes the cursor extremely thin, I would go for the custom shape!Camarillo
L
618

In Layout

<EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textCursorDrawable="@drawable/color_cursor"
    />

Then create drawalble xml: color_cursor

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

You have a white color cursor on EditText property.

Lipophilic answered 15/3, 2013 at 11:22 Comment(9)
Attribute "textCursorDrawable" is only used in API level 12 and higherNymphomania
This is the correct answer. Not sure why so many people out there think that setting cursor to "@null" seems like a good ideaMimi
above answer, set textCursorDrawable as @null results look fine, but cursor's orientation does not make sense, however, this answer works really great. Really ThanksPricket
Can we use same excel with different colors for cursor?Bornie
What if background is white?Akkad
@GregEnnis because that answer makes them save 42 seconds compared to this oneCelluloid
This IS the solution, thank you @star18bit. I have to mention something though, if the user doesn't care about the color of the cursor, he can set the textCursorDrawable to null and the default one will be displayed, however, for setting the color, this solution is the correct one as some users might be setting @color/cursor_color and seeing nothing, because the attribute textCursorDrawable accepts drawable and not color.Washery
setting textCursorDrawable as @null will make the color of cursor the same with textColorHint if it is defined so this is the best answer for me :)Efthim
we can control width of the cursor using this solution, but @null makes it very thinIchang
G
94

It appears as if all the answers go around the bushes.

In your EditText, use the property:

android:textCursorDrawable="@drawable/black_cursor"

and add the drawable black_cursor.xml to your resources, as follows:

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

This is also the way to create more diverse cursors, if you need.

Groundmass answered 28/5, 2012 at 19:59 Comment(4)
This does not work on Android 4.2 Jelly Bean... The cursor disappears, @null is the way to go.Rosenquist
@Rosenquist This seems to work for me on 4.2 JB just fine at the themes level.Monomerous
Android 4.2.2 works fine. Don't forget to add <solid android:color="#000000"/> in black_cursor.xmlMaenad
Attribute "textCursorDrawable" is only used in API level 12 and higherNymphomania
E
80

There is a new way to change cursor color in latest Appcompact v21
Just change colorAccent in style like this:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->

    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#088FC9</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#088FC9</item>

    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <!-- THIS IS WHAT YOU'RE LOOKING FOR -->
    <item name="colorAccent">#0091BC</item> 
</style>

Then apply this style on your app theme or activities.

Update: this way only works on API 21+
Update 2: I'm not sure the minimum android version that it can work.
Tested by android version:

2.3.7 - didn't work
4.4.4 - worked
5.0 - worked
5.1 - worked
Eliott answered 20/3, 2015 at 2:53 Comment(5)
I'm afraid the answer is no. I tested on API 18 device and it doesn't work.Eliott
Working on my Sony Experia. PreLollipop (4.4.4). Also using AppCompat library. :)Sonnnie
Doesn't work for API 24/Android 7.0. colorAccent changes e.g. the line at the bottom of an EditText but it doesn't touch the actual cursor color. Oh, and there's no "v21" anymore of course.Beggarly
you should not change the accent colour of your application because you want to change the colour of a cursor.Queston
@oziomajnr, yes, we should apply custom theme to, for instance, fragment, not whole application.Landin
C
46

I found the answer :)

I've set the Theme's editText style to:

<item name="android:editTextStyle">@style/myEditText</item>

Then I've used the following drawable to set the cursor:

`

<style name="myEditText" parent="@android:style/Widget.Holo.Light.EditText">
    <item name="android:background">@android:drawable/editbox_background_normal</item>
    <item name="android:textCursorDrawable">@android:drawable/my_cursor_drawable</item>
    <item name="android:height">40sp</item>
</style>

`

android:textCursorDrawable is the key here.

Covarrubias answered 30/8, 2011 at 3:57 Comment(3)
https://mcmap.net/q/65225/-vertical-line-using-xml-drawable might be of use to anyone wanting to make a cursor drawable that is just a vertical line :)Seasickness
can you pls tell how can we set the cursor color in programmaticallyBennybenoit
I had an issue when I named the item android:editTextStyle, but changing it to editTextStyle fixed it. See https://mcmap.net/q/57908/-android-set-edit-text-style-globally-in-theme-doesn-39-t-workPreussen
T
27

For anyone that needs to set the EditText cursor color dynamically, below you will find two ways to achieve this.


First, create your cursor drawable:

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

Set the cursor drawable resource id to the drawable you created (source)):

try {
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(yourEditText, R.drawable.cursor);
} catch (Exception ignored) {
}

To just change the color of the default cursor drawable, you can use the following method:

    public static void setTextCursorColor(TextView textView, @ColorInt int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            final Drawable drawable = textView.getTextCursorDrawable();
            drawable.setTint(color);
            textView.setTextCursorDrawable(drawable);
        } else try {
            Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            fCursorDrawableRes.setAccessible(true);
            int   mCursorDrawableRes = fCursorDrawableRes.getInt(textView);
            Field fEditor            = TextView.class.getDeclaredField("mEditor");
            fEditor.setAccessible(true);
            Object   editor          = fEditor.get(textView);
            Class<?> clazz           = editor.getClass();
            Field    fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
            fCursorDrawable.setAccessible(true);

            Drawable[] drawables = new Drawable[2];
            Resources  res       = textView.getContext().getResources();
            drawables[0] = res.getDrawable(mCursorDrawableRes);
            drawables[1] = res.getDrawable(mCursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            fCursorDrawable.set(editor, drawables);
        } catch (final Throwable throwable) {
            if (DEBUG) throw new RuntimeException("can't set text cursor color", throwable);
        }
    }
Tuggle answered 9/9, 2015 at 8:47 Comment(3)
It really bothers me that this works. AppCompatEditText already has setSupportBackgroundTintList, so wouldn’t it be fairly simple to add something like setSupportCursorTintList?Peggiepeggir
@Jared Rummler your solution worked for the cursor, but the droplet that appears below the cursor (when you select the text it appears two of them) are still of the original color. Can you help me with this?Drawn
Your 3. approach did not work in Android 9 but fine for below versions.Science
H
13

Late to the party,Here's is my answer,

This is for the people who are not looking to change the colorAccent in their parent theme,but wants to change EditText attributes!

This answer demos how to change ......

  1. Bottom line color
  2. Cursor color
  3. Cursor pointer color (I used my custom image).......... of EditText using style applied to the Activity theme.

enter image description here

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hey" />

Example:

<style name="AppTheme.EditText" parent="@style/Widget.AppCompat.EditText">
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">#8AFFFFFF</item>
    <item name="android:background">@drawable/edit_text_background</item> // background (bottom line at this case)
    <item name="android:textCursorDrawable">@color/white</item>  // Cursor
    <item name="android:textSelectHandle">@drawable/my_white_icon</item> // For pointer normal state and copy text state
    <item name="android:textSelectHandleLeft">@drawable/my_white_icon</item>
    <item name="android:textSelectHandleRight">@drawable/my_white_icon</item>
</style>

Now create a drawable(edit_text_background) add a resource xml for the background!You can customize as you want!

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="0dp"
        android:left="-3dp"   
        android:right="-3dp"
        android:top="-3dp">

        <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="@color/white"/>
        </shape>
    </item>
    </layer-list>

Now as you did set this style in your Activity theme.

Example :

In your Activity you have a theme,set this custom editText theme to that.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Your Theme data -->
    <item name="editTextStyle">@style/AppTheme.EditText</item> // inculude this
</style>
Hydrolyze answered 2/2, 2017 at 0:48 Comment(4)
<item name="editTextStyle">@style/AppTheme.EditText</item> // inculude this no effectIsla
is it AppCompatEditText ?Potemkin
oh,I'am wrong. I wrote wrong attr android:editTextSteyle ,right attr is editTextStyleIsla
<item name="android:textCursorDrawable">@color/white</item> doesn't workEleaseeleatic
S
10

Wow I am real late to this party but it has had activity 17 days ago It would seam we need to consider posting what version of Android we are using for an answer so as of now this answer works with Android 2.1 and above Go to RES/VALUES/STYLES and add the lines of code below and your cursor will be black

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!--<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">-->
    <!-- Customize your theme here. -->
    <item name="colorControlActivated">@color/color_Black</item>
    <!--Sets COLOR for the Cursor in EditText  -->
</style>

You will need a this line of code in your RES/COLOR folder

<color name="color_Black">#000000</color>

Why post this late ? It might be nice to consider some form of categories for the many headed monster Android has become!

Shannon answered 27/8, 2017 at 0:39 Comment(1)
Attribute requires API level 21 not 7 (2.1)Preussen
W
9
Edittext cursor color you want changes your color.
   <EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textCursorDrawable="@drawable/color_cursor"
    />

Then create drawalble xml: color_cursor

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <size android:width="3dp" />
    <solid android:color="#FFFFFF"  />
</shape>
Waggle answered 7/12, 2016 at 12:9 Comment(0)
C
7

For me I modified both the AppTheme and a value colors.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorControlNormal">@color/yellow</item>
    <item name="colorAccent">@color/yellow</item>
</style>

Here is the colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="yellow">#B7EC2A</color>
</resources>

I took out the android:textCursorDrawable attribute to @null that I placed inside the editText style. When I tried using this, the colors would not change.

Candiot answered 22/2, 2016 at 16:53 Comment(1)
Yes that works but then you also change other theme elements when all you might need is to change the cursor color.Desjardins
H
7

Use this

android:textCursorDrawable="@color/white"
Halberd answered 9/8, 2017 at 11:40 Comment(3)
The cursor disappears in my device, so use a drawable instead of direct set the color.Pleuron
this is useful if you want to hide the cursor, if you say that you'll probably get more votes!Bestrew
This is not proper solution. This will disappeared the cursor before typing and between typing it's not proper to show if we change color.Selvage
A
6

We can do it in meterial theme as following:

<style name="Theme.App" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    ...
    <item name="android:colorControlNormal">#ff0000</item>
    <item name="android:colorControlActivated">#ff0000</item>
    <item name="android:colorControlHighlight">#ff0000</item>
    ...
</style>

And if you want to change checkbox and radio colors too, add the following line:

<item name="colorAccent">#ff0000</item>

I've tested in Android API 21+

Acculturation answered 23/4, 2021 at 15:45 Comment(0)
U
5

The only valid answer should be to change the theme of the activity: <item name="colorAccent">#000000</item> You should not use the android:textCursorDrawable to @null because this only concerns the cursor itself but not the pin below the cursor if you want to drag that cursor. The theming solution is the most serious one.

Unconsidered answered 16/10, 2017 at 12:5 Comment(0)
A
5

Here @Jared Rummler's programatic setCursorDrawableColor() version adapted to work also on Android 9 Pie.

@SuppressWarnings({"JavaReflectionMemberAccess", "deprecation"})
public static void setCursorDrawableColor(EditText editText, int color) {

    try {
        Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResField.setAccessible(true);
        int cursorDrawableRes = cursorDrawableResField.getInt(editText);
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editor = editorField.get(editText);
        Class<?> clazz = editor.getClass();
        Resources res = editText.getContext().getResources();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Field drawableForCursorField = clazz.getDeclaredField("mDrawableForCursor");
            drawableForCursorField.setAccessible(true);
            Drawable drawable = res.getDrawable(cursorDrawableRes);
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawableForCursorField.set(editor, drawable);
        } else {
            Field cursorDrawableField = clazz.getDeclaredField("mCursorDrawable");
            cursorDrawableField.setAccessible(true);
            Drawable[] drawables = new Drawable[2];
            drawables[0] = res.getDrawable(cursorDrawableRes);
            drawables[1] = res.getDrawable(cursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            cursorDrawableField.set(editor, drawables);
        }
    } catch (Throwable t) {
        Log.w(TAG, t);
    }
}
Abm answered 9/3, 2019 at 20:21 Comment(2)
java.lang.NoSuchFieldException: No field mDrawableForCursor on Android 9.Thigmotropism
This solution doesn't work anymore. See developer.android.com/about/versions/pie/…Cumulation
Z
5
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item> -- change this one
</style>

Go to styles.xml and change the color accent and this will influence the cursor from the edittext box

Zooid answered 6/1, 2020 at 1:57 Comment(0)
L
4

that's called colorAccent in Android.

go to res -> values -> styles.xml add

<item name="colorAccent">#FFFFFF</item>

if not exists.

Lauralee answered 9/7, 2019 at 23:1 Comment(0)
E
3

editcolor.xml

android:textCursorDrawable="@drawable/editcolor"

In xml file set color code of edittext background color

Ellisellison answered 28/4, 2017 at 5:20 Comment(1)
Just remove the corsor which is blinking in edittextEllisellison
C
3

After a lot of time spent trying all these technique in a Dialog, I finally had this idea : attach the theme to the Dialog itself and not to the TextInputLayout.

<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorWhite</item>
    <item name="colorAccent">@color/colorPrimary</item>

</style>

inside onCreate :

public class myDialog extends Dialog {

private Activity activity;
private someVars;

public PopupFeedBack(Activity activity){
    super(activity, R.style.AppTheme_Dialog);
    setContentView(R.layout.myView);
    ....}}

cheers :)

Chaussure answered 10/4, 2020 at 14:44 Comment(0)
C
3

Pay attention to your colorAccent in your current Activity/fragment/Dialog, defined in Styles... ;) cursor color is related to it.

Chaussure answered 10/4, 2020 at 14:48 Comment(0)
Y
2

Another simple solution would be to go to res>values>colors.xml in your project folder and edit the value of the color accent to the color you prefer

<color name="colorAccent">#000000</color>

The code above changes your cursor to black.

Young answered 31/1, 2019 at 6:46 Comment(1)
Thanks, that's exactly what I was looking forBackdate
D
2

In API 21 and above:

<com.google.android.material.textfield.TextInputLayout                
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:theme="@style/CursorColor">

// In colors.xml
<style name="CursorColor">
    <item name="colorPrimary">@color/black</item>
</style>>
Discommode answered 6/4, 2022 at 23:17 Comment(1)
The most simple solution!Landin
F
1

Its even easier than that.

<style name="MyTextStyle">
    <item name="android:textCursorDrawable">#000000</item>
</style>

This works in ICS and beyond. I haven't tested it in other versions.

Frae answered 11/6, 2013 at 23:5 Comment(3)
beware, if you are going to apply this style to your EditText(this does not have a parent style, which should be the default pertaining to your theme), you will loose all other styling that comes from the Holo Theme.Internuncio
Isn't it the same as "@null" value ?Antoniettaantonin
you can add a style juste to a view, which overrides the activity's theme.Unconsidered
S
1

are you want specific color you must use AppCompatEditText then backround set null

works for me

<android.support.v7.widget.AppCompatEditText
    android:background="@null"
    android:textCursorDrawable="@color/cursorColor"/>

See this gist

Supposititious answered 19/12, 2018 at 7:56 Comment(0)
B
1

This is how i solved it

Step1: Update the latest material

implementation 'com.google.android.material:material:1.1.0'

Step2: type reference TextInputLayout.OutlinedBox.Dense, Any...

    <style name="TextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">
        <item name="boxStrokeColor">@color/app_color_main</item>
        <item name="hintTextColor">@color/app_color_main</item>
        <item name="android:theme">@style/exampleCursor</item>
    </style>

Step3: [important to change cursor color] - set colorControlActivated property to desired cursor color

    <style name="exampleCursor" parent="ThemeOverlay.MaterialComponents.TextInputEditText.OutlinedBox">
        <item name="colorControlActivated">@color/app_color_main</item>
    </style>

more detail here:

Boxcar answered 19/7, 2023 at 9:0 Comment(0)
R
1

2023 - Compose Edition

You can change the cursor color with cursorBrush.

Sample Usage

BasicTextField(
            
            ...
            cursorBrush = SolidColor(Transparent),
            ...
        )
Remise answered 18/10, 2023 at 17:53 Comment(0)
A
0

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#36f0ff</item>
    <item name="colorPrimaryDark">#007781</item>
    <item name="colorAccent">#000</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

change t he color of colorAccent in styles.xm, that's it simple

Anatol answered 25/8, 2016 at 14:26 Comment(0)
O
0

If using style and implement

colorControlActivate

replace its value other that color/white.

Overtime answered 19/9, 2019 at 1:19 Comment(0)
J
0

You can directly set cursor color since 1.10.0 version.

Developer quote:

It's fixed in c598ccd. We added an attribute and a setter to set the cursor color under errors. The change is supposed to be published with upcoming 1.10.0-alpha02.

Add the following code to your TextInputLayout style:

<item name="cursorErrorColor">@color/error_color</item>
<item name="cursorColor">@color/accent_color</item>

or to your TextInputLayout view:

<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cursorErrorColor="@color/error_color"
app:cursorColor="@color/accent_color"
...
Jump answered 21/12, 2023 at 13:58 Comment(0)
E
-1
<style name="CustomTheme" parent="AppTheme">
    <item name="colorAccent">@color/yourColor</item>
</style>

Add this in styles and then in the Edittext set the theme as follows:

android:theme="@style/CustomTheme"

And thats it!

Elviaelvie answered 19/1, 2022 at 18:15 Comment(0)
G
-2

you can use code below in layout

android:textCursorDrawable="@color/red"
        android:textColor="@color/black
Godolphin answered 27/9, 2019 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.