和尚我有个小需求是根据主题配色更改 EditText 中输入框光标的颜色,网上查了一些资料,大部分都是直接用的 xml 方式在做调整,但是和尚我需要的是在 Java 代码中动态调整光标颜色。 虽然是一个很简单的东西,但是和尚我在测试中还是遇到了不少的小问题,现在简单整理一下,希望对于遇到相同问题的朋友有所帮助。
和尚我的测试步骤如下:
<EditText android:id="@+id/test_et1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="18dp" android:background="@null" android:hint="默认光标颜色,色值 #13B7F6" />
<EditText android:id="@+id/test_et2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="18dp" android:background="@null" android:hint="xml 设置光标颜色,色值 #F54343" android:textCursorDrawable="@drawable/editext_cursor" />
<?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="@color/red" /> </shape>
<EditText android:id="@+id/test_et3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="18dp" android:background="@null" android:hint="Java 设置光标颜色(不正常)为灰色" android:textCursorDrawable="@null" />
GradientDrawable myGrad2 = new GradientDrawable(); myGrad2.setColor(getResources().getColor(R.color.cmbkb_limit_buy_green)); myGrad2.setSize(4, 40); try { Field f = TextView.class.getDeclaredField("mCursorDrawableRes"); f.setAccessible(true); f.set(et3, myGrad2); } catch (Exception ignored) { // TODO: handle exception
Tips: 造成失败的原因有两个,第一个不可设置 android:textCursorDrawable="@null" ,这样光标颜色默认是根据字体颜色一致;第二个是不可以设置 new GradientDrawable() ,并不能直接调整光标颜色。
<EditText android:id="@+id/test_et4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="18dp" android:background="@null" android:hint="Java 设置光标颜色(正常),色值 #00CC00" android:textCursorDrawable="@drawable/editext_cursor" />
GradientDrawable myGrad1 = (GradientDrawable) getResources().getDrawable(R.drawable.editext_cursor); myGrad1.setColor(getResources().getColor(R.color.cmbkb_limit_buy_green)); myGrad1.setSize(4, 20); try { Field f = TextView.class.getDeclaredField("mCursorDrawableRes"); f.setAccessible(true); f.set(et4, myGrad1); } catch (Exception ignored) {