There weren't any simple way to change EditText cursor color programmatically, so here it is.
Should work with API level 15 and newer.
Should work with API level 15 and newer.
B4X:
Private Sub Class_Globals
Private jo As JavaObject
End Sub
'Support for Android 4.0.x
'stackoverflow.com/questions/25996032/how-to-change-programmatically-edittext-cursor-color-in-android
Public Sub Initialize
jo = Me
End Sub
Public Sub SetColor (EditText As EditText, Color As Int)
jo.RunMethod("setCursorColor", Array(EditText,Color))
End Sub
#If Java
import android.widget.EditText;
import android.widget.TextView;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import java.lang.reflect.Field;
import android.support.v4.content.ContextCompat;
import android.graphics.PorterDuff;
import android.os.Build;
public void setCursorColor(EditText editText, @ColorInt int color) {
try {
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(editText);
Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
Drawable[] drawables = {drawable, drawable};
if (Build.VERSION.SDK_INT == 15) {
Class<?> drawableFieldClass = TextView.class;
field = drawableFieldClass.getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editText, drawables);
} else {
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(editText);
field = editor.getClass().getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editor, drawables);
}
} catch (Exception e) {
}
}
#End If