🐙

.NET MAUIのカーソル変更

2024/08/22に公開

ダークモードでデフォルトの基調色だとカーソルが見えにくいのですが、
今のバージョンではそういう対策がまだ入っていないようなので。
MauiProgram.csを次のようにします。

using Microsoft.Extensions.Logging;

#if __ANDROID__
using Microsoft.Maui.Controls.Compatibility.Platform.Android;
#endif

namespace AppMaui {
  public static class MauiProgram {
    public static MauiApp CreateMauiApp() {
      var builder = MauiApp.CreateBuilder();
      builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts => {
          fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
          fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        });

#if DEBUG
  		builder.Logging.AddDebug();
#endif

#if __ANDROID__

      // Entry(シングルライン)
      Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("EntryCursorColor", (handler, view) => {
        if(OperatingSystem.IsAndroidVersionAtLeast(29)) {
          var at = Application.Current?.PlatformAppTheme;
          var cursorColor = at == AppTheme.Dark ? Colors.White : Colors.Black;
          handler?.PlatformView?.TextCursorDrawable?.SetTint(cursorColor.ToAndroid());
        }
      });

      // Editor(マルチライン)
      Microsoft.Maui.Handlers.EditorHandler.Mapper.AppendToMapping("EditorCursorColor", (handler, view) => {
        if(OperatingSystem.IsAndroidVersionAtLeast(29)) {
          var at = Application.Current?.PlatformAppTheme;
          var cursorColor = at == AppTheme.Dark ? Colors.White : Colors.Black;
          handler?.PlatformView?.TextCursorDrawable?.SetTint(cursorColor.ToAndroid());
        }
      });

#endif

      return builder.Build();
    }
  }
}

Discussion