In android we can change the cursor color via:
android:textCursorDrawable="@drawable/black_color_cursor"
.
How can we do this dynamically?
In my case I have set cursor drawable to white, but i need to change black How to do ?
// Set an EditText view to get user input
final EditText input = new EditText(nyactivity);
input.setTextColor(getResources().getColor(R.color.black));
Using some reflection did the trick for me
Java:
// 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>
Here is a method that you can use that doesn't need an 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) {
}
}
android:textCursorDrawable="@null"
Then in the application:
final EditText input = new EditText(nyactivity);
input.setTextColor(getResources().getColor(R.color.black));
Get from here
This is a rewritten version of the function from @Jared Rummler with a couple of improvements:
getDrawable(Context, int)
function sience the getDrawable(int)
is deprecated for API 22 and above.private static final Field
sEditorField,
sCursorDrawableField,
sCursorDrawableResourceField;
static {
Field editorField = null;
Field cursorDrawableField = null;
Field cursorDrawableResourceField = null;
boolean exceptionThrown = false;
try {
cursorDrawableResourceField = TextView.class.getDeclaredField("mCursorDrawableRes");
cursorDrawableResourceField.setAccessible(true);
final Class<?> drawableFieldClass;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
drawableFieldClass = TextView.class;
} else {
editorField = TextView.class.getDeclaredField("mEditor");
editorField.setAccessible(true);
drawableFieldClass = editorField.getType();
}
cursorDrawableField = drawableFieldClass.getDeclaredField("mCursorDrawable");
cursorDrawableField.setAccessible(true);
} catch (Exception e) {
exceptionThrown = true;
}
if (exceptionThrown) {
sEditorField = null;
sCursorDrawableField = null;
sCursorDrawableResourceField = null;
} else {
sEditorField = editorField;
sCursorDrawableField = cursorDrawableField;
sCursorDrawableResourceField = cursorDrawableResourceField;
}
}
public static void setCursorColor(EditText editText, int color) {
if (sCursorDrawableField == null) {
return;
}
try {
final Drawable drawable = getDrawable(editText.getContext(),
sCursorDrawableResourceField.getInt(editText));
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
sCursorDrawableField.set(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
? editText : sEditorField.get(editText), new Drawable[] {drawable, drawable});
} catch (Exception ignored) {
}
}
private static Drawable getDrawable(Context context, int id) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return context.getResources().getDrawable(id);
} else {
return context.getDrawable(id);
}
}
Kotlin version, works from api 14 to api 32
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.VectorDrawable
import android.os.Build
import android.util.TypedValue
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import java.lang.reflect.Field
fun TextView.setCursorDrawableColor(@ColorInt color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
textCursorDrawable = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(color, color))
.apply { setSize(2.spToPx(context).toInt(), textSize.toInt()) }
return
}
try {
val editorField = TextView::class.java.getFieldByName("mEditor")
val editor = editorField?.get(this) ?: this
val editorClass: Class<*> = if (editorField != null) editor.javaClass else TextView::class.java
val cursorRes = TextView::class.java.getFieldByName("mCursorDrawableRes")?.get(this) as? Int ?: return
val tintedCursorDrawable = ContextCompat.getDrawable(context, cursorRes)?.tinted(color) ?: return
val cursorField = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
editorClass.getFieldByName("mDrawableForCursor")
} else {
null
}
if (cursorField != null) {
cursorField.set(editor, tintedCursorDrawable)
} else {
editorClass.getFieldByName("mCursorDrawable", "mDrawableForCursor")
?.set(editor, arrayOf(tintedCursorDrawable, tintedCursorDrawable))
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
fun Class<*>.getFieldByName(vararg name: String): Field? {
name.forEach {
try{
return this.getDeclaredField(it).apply { isAccessible = true }
} catch (t: Throwable) { }
}
return null
}
fun Drawable.tinted(@ColorInt color: Int): Drawable = when {
this is VectorDrawableCompat -> {
this.apply { setTintList(ColorStateList.valueOf(color)) }
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && this is VectorDrawable -> {
this.apply { setTintList(ColorStateList.valueOf(color)) }
}
else -> {
DrawableCompat.wrap(this)
.also { DrawableCompat.setTint(it, color) }
.let { DrawableCompat.unwrap(it) }
}
}
fun Number.spToPx(context: Context? = null): Float {
val res = context?.resources ?: android.content.res.Resources.getSystem()
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), res.displayMetrics)
}
We managed to do it by:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With