When changing the cursor color, it is advisable to adjust the background color of the selected text and the selection cursor color in order to maintain visual consistency. Here’s the way how to achieve this on Android
API 29
and later:
In shared .NET MAUI code create subclass of Entry
, so you can add additional properties/bindings etc, for example create MyEntryView.cs
:
using Microsoft.Maui.Controls.Shapes;
using MauiEntry = Microsoft.Maui.Controls.Entry;
namespace MyLibrary;
public class MyEntryView : MauiEntry
{
public Color CursorColor { get; set; }
}
In shared .NET MAUI code create MyEntryHandler.cs
:
using Microsoft.Maui.Handlers;
namespace MyLibrary;
public partial class MyEntryHandler : EntryHandler { } //empty
Create MyEntryHandler.cs
in the Platforms/Android
folder:
using Android.Graphics;
using AndroidX.AppCompat.Widget;
using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
namespace MyLibrary;
public partial class MyEntryHandler : EntryHandler
{
protected override void ConnectHandler(AppCompatEditText platformView)
{
base.ConnectHandler(platformView);
var v = VirtualView as MyEntryView;
if (v != null)
{
PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent); //hide underline
if (v.CursorColor != null && OperatingSystem.IsAndroidVersionAtLeast(29))
{
//sets cursor color
//for older api versions app will set cursor color according to colorAccent from colors.xml
PlatformView.TextCursorDrawable.SetTint(v.CursorColor.ToPlatform());
//sets color of the selection cursors
var f = new BlendModeColorFilter(v.CursorColor.ToPlatform(), Android.Graphics.BlendMode.SrcIn);
PlatformView.TextSelectHandleLeft.SetColorFilter(f);
PlatformView.TextSelectHandleRight.SetColorFilter(f);
PlatformView.TextSelectHandle.SetColorFilter(f);
//set color of selected text
//you can expose the value of alpha to MyEntryView if you like
PlatformView.SetHighlightColor(v.CursorColor.WithAlpha((float) 0.4).ToPlatform());
}
}
}
protected override void DisconnectHandler(AppCompatEditText platformView)
{
base.DisconnectHandler(platformView);
platformView.Dispose();
}
}
Register handlers in CreateMauiApp
method in the MauiProgram
class like:
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler(typeof(Entry), typeof(MyEntryHandler));
});
Create instance of MyEntry
and place it somewhere in the view tree and that's it. Example of MyEntry
:
var e = new MyEntry
{
CursorColor = Colors.Orange
//set other properties as well to fit your specification ...
};
Example of how it appears on Android
: