如何在 android 中以编程方式更改 Edittext 光标颜色?

新手上路,请多包涵

在 android 中,我们可以通过以下方式更改光标颜色:

android:textCursorDrawable="@drawable/black_color_cursor"

我们如何动态地做到这一点?

就我而言,我已将可绘制光标设置为白色,但我需要更改为黑色怎么办?

     // Set an EditText view to get user input
    final EditText input = new EditText(nyactivity);
    input.setTextColor(getResources().getColor(R.color.black));

原文由 Amit Prajapati 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 630
2 个回答

使用一些反射对我有用

爪哇:

 // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(yourEditText, R.drawable.cursor);

XML:

 <?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>


这是您可以使用的不需要 XML 的方法:

 public static void setCursorColor(EditText view, @ColorInt int color) {
  try {
    // Get the cursor resource id
    Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
    field.setAccessible(true);
    int drawableResId = field.getInt(view);

    // Get the editor
    field = TextView.class.getDeclaredField("mEditor");
    field.setAccessible(true);
    Object editor = field.get(view);

    // Get the drawable and set a color filter
    Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
    drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    Drawable[] drawables = {drawable, drawable};

    // Set the drawables
    field = editor.getClass().getDeclaredField("mCursorDrawable");
    field.setAccessible(true);
    field.set(editor, drawables);
  } catch (Exception ignored) {
  }
}

原文由 Jared Rummler 发布,翻译遵循 CC BY-SA 3.0 许可协议

android:textCursorDrawable="@null"

然后在应用程序中:

 final EditText input = new EditText(nyactivity);
input.setTextColor(getResources().getColor(R.color.black));

从这里出发

原文由 Orest Savchak 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题