Skip to content

Instantly share code, notes, and snippets.

@jaredrummler
Created September 1, 2016 17:56
Show Gist options
  • Save jaredrummler/2317620559d10ac39b8218a1152ec9d4 to your computer and use it in GitHub Desktop.
Save jaredrummler/2317620559d10ac39b8218a1152ec9d4 to your computer and use it in GitHub Desktop.
Set the color of the handles shown when you select text in a TextView on Android
// Tested on Android Nougat. Should work on previous versions of Android.
// It's ugly but should get the job done
/**
* Set the color of the handles when you select text in a
* {@link android.widget.EditText} or other view that extends {@link TextView}.
*
* @param view
* The {@link TextView} or a {@link View} that extends {@link TextView}.
* @param color
* The color to set for the text handles
*/
public static void colorHandles(TextView view, int color) {
try {
Field editorField = TextView.class.getDeclaredField("mEditor");
if (!editorField.isAccessible()) {
editorField.setAccessible(true);
}
Object editor = editorField.get(view);
Class<?> editorClass = editor.getClass();
String[] handleNames = {"mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter"};
String[] resNames = {"mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes"};
for (int i = 0; i < handleNames.length; i++) {
Field handleField = editorClass.getDeclaredField(handleNames[i]);
if (!handleField.isAccessible()) {
handleField.setAccessible(true);
}
Drawable handleDrawable = (Drawable) handleField.get(editor);
if (handleDrawable == null) {
Field resField = TextView.class.getDeclaredField(resNames[i]);
if (!resField.isAccessible()) {
resField.setAccessible(true);
}
int resId = resField.getInt(view);
handleDrawable = view.getResources().getDrawable(resId);
}
if (handleDrawable != null) {
Drawable drawable = handleDrawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
handleField.set(editor, drawable);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@japl600
Copy link

japl600 commented Nov 12, 2019

Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment