如何在安卓应用中使用代码更改光标
大家好,我一直在尝试通过编程方式更改我的安卓应用中的光标,但遇到了一些困难。有人有通过代码而非XML让光标看起来不同的技巧或方法吗?非常感谢任何帮助或示例!谢谢!
Samuel Bishop
February 8, 2026 at 09:01 PM
大家好,我一直在尝试通过编程方式更改我的安卓应用中的光标,但遇到了一些困难。有人有通过代码而非XML让光标看起来不同的技巧或方法吗?非常感谢任何帮助或示例!谢谢!
添加评论
评论 (5)
Honestly, this is one of those annoying things Android doesn't support well out of the box. You might wanna check libraries on GitHub that handle custom cursors.
You can do it by accessing the TextView's mCursorDrawable via reflection and setting your drawable programmatically. It's a bit hacky but works for most versions.
我刚刚使用了 Spannable 来改变文本外观,但对于光标本身,Android 并不容易实现。你试过在 XML 中使用 android:textCursorDrawable 吗?对于代码来说,这有点有限。
我实际上尝试过通过编程方式将 textCursorDrawable 设置为颜色可绘制资源来更改光标颜色。这在某种程度上有效,但并非在所有设备上都完美。
是的,在安卓中动态更改光标并不是非常简单。通常,你需要操作 EditText 并使用 setCursorVisible,或者在某些 API 级别上使用自定义光标图像。