Cómo cambiar el color de la burbuja (bajo cursor) en EditView (PROGRAMATICALLY)?
Tengo EditView y quiero cambiar el color PROGRAMATICALLY en el código .
Para cambiar el color del cursor uso este código .
- Android ContentProvider Esquema de URI para notificar a CursorAdapters escuchando consultas de OUTER JOIN
- Android desventajas de no cerrar el cursor
- ¿Por qué los Cursores Android comienzan antes de la primera fila de resultados y terminan después de la última fila?
- ¿Es apropiado SQL o acceso general a archivos en el hilo principal de la interfaz de usuario de Android?
- ¿Cursor.getString () coacciona un int en una cadena?
Pero ¿Cómo cambiar el color del círculo en EditView PROGRAMATICAMENTE en el código ?
- Android - ¿Puedes actualizar un Cursor para los resultados de SQLite?
- Recyclerview + Proveedor de contenido + CursorLoader
- Cómo crear Cursor de JSONArray?
- Cómo probar si el cursor está vacío en una consulta SQLiteDatabase
- ¿Qué bandera usar en SimpleCursorAdapter?
- Limitar el número de filas devueltas desde sqlite
- ¿Cómo mantener la posición de ListView al usar las nuevas API de Loader?
- Panal y cursores (frustrado)
Tendrá que utilizar la reflexión para tintar las manijas selectas (burbujas). Escribí la siguiente clase esta mañana:
Ejemplo de uso:
try { EditTextTint.applyColor(editText, Color.CYAN); } catch (EditTextTint.EditTextTintError e) { e.printStackTrace(); }
EditTextTint.java :
import android.content.res.Resources; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.widget.EditText; import android.widget.TextView; import java.lang.reflect.Field; /** * Tint the cursor and select handles of an {@link EditText} programmatically. */ public class EditTextTint { /** * Set the cursor and handle colors for an {@link EditText} programmatically. * * @param editText * The {@link EditText} to tint * @param color * The color to apply for the cursor and select handles * @throws EditTextTintError * If an error occured while attempting to tint the view. */ public static void applyColor(@NonNull EditText editText, @ColorInt int color) throws EditTextTintError { EditTextTint editTextTint = new Builder(editText) .setCursorColor(color) .setSelectHandleLeftColor(color) .setSelectHandleRightColor(color) .setSelectHandleMiddleColor(color) .build(); editTextTint.apply(); } private final EditText editText; private final Integer cursorColor; private final Integer selectHandleLeftColor; private final Integer selectHandleRightColor; private final Integer selectHandleMiddleColor; private EditTextTint(Builder builder) { editText = builder.editText; cursorColor = builder.cursorColor; selectHandleLeftColor = builder.selectHandleLeftColor; selectHandleRightColor = builder.selectHandleRightColor; selectHandleMiddleColor = builder.selectHandleMiddleColor; } /** * Sets the color for the cursor and handles on the {@link EditText editText}. * * @throws EditTextTintError * if an error occurs while tinting the view. */ public void apply() throws EditTextTintError { try { Resources res = editText.getContext().getResources(); // Get the editor Field field = TextView.class.getDeclaredField("mEditor"); field.setAccessible(true); Object editor = field.get(editText); if (cursorColor != null) { // Get the cursor drawable, tint it, and set it on the TextView Editor field = TextView.class.getDeclaredField("mCursorDrawableRes"); field.setAccessible(true); int cursorDrawableRes = field.getInt(editText); Drawable cursorDrawable = res.getDrawable(cursorDrawableRes).mutate(); cursorDrawable.setColorFilter(cursorColor, PorterDuff.Mode.SRC_IN); Drawable[] drawables = {cursorDrawable, cursorDrawable}; field = editor.getClass().getDeclaredField("mCursorDrawable"); field.setAccessible(true); field.set(editor, drawables); } String[] resFieldNames = {"mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes"}; String[] drawableFieldNames = {"mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter"}; Integer[] colors = {selectHandleLeftColor, selectHandleRightColor, selectHandleMiddleColor}; for (int i = 0; i < resFieldNames.length; i++) { Integer color = colors[i]; if (color == null) { continue; } String resFieldName = resFieldNames[i]; String drawableFieldName = drawableFieldNames[i]; field = TextView.class.getDeclaredField(resFieldName); field.setAccessible(true); int selectHandleRes = field.getInt(editText); Drawable selectHandleDrawable = res.getDrawable(selectHandleRes).mutate(); selectHandleDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); field = editor.getClass().getDeclaredField(drawableFieldName); field.setAccessible(true); field.set(editor, selectHandleDrawable); } } catch (Exception e) { throw new EditTextTintError("Error applying tint to " + editText, e); } } public static class Builder { final EditText editText; Integer cursorColor; Integer selectHandleLeftColor; Integer selectHandleRightColor; Integer selectHandleMiddleColor; public Builder(@NonNull EditText editText) { this.editText = editText; } public Builder setCursorColor(@ColorInt int cursorColor) { this.cursorColor = cursorColor; return this; } public Builder setSelectHandleLeftColor(@ColorInt int selectHandleLeftColor) { this.selectHandleLeftColor = selectHandleLeftColor; return this; } public Builder setSelectHandleRightColor(@ColorInt int selectHandleRightColor) { this.selectHandleRightColor = selectHandleRightColor; return this; } public Builder setSelectHandleMiddleColor(@ColorInt int selectHandleMiddleColor) { this.selectHandleMiddleColor = selectHandleMiddleColor; return this; } public EditTextTint build() { return new EditTextTint(this); } } public static class EditTextTintError extends Exception { public EditTextTintError(String message, Throwable cause) { super(message, cause); } } }
Nota: Esto debería funcionar desde Jelly Bean hasta Nougat. Sin embargo, ya que utiliza la reflexión para obtener y establecer los campos privados esto puede romperse en futuras versiones de Android o si un fabricante ha realizado cambios en EditText.
El siguiente método funciona para todos los cursores burbuja, como izquierda, derecha y centro. Quiero decir, junto a tu petición, funciona tanto para la izquierda como para la derecha.
Por ejemplo;
Puede cambiar ese método para sólo colorear el identificador central quitando los nombres de campo izquierdo y derecho en las dos matrices.
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(); } }
Pruebe esto: cambie el valor en el archivo values / colors.xml
<color name="colorAccent">#263238</color>
Cambie este código de color # 263238 a su propio código de color, para que sea aplicable a todo el proyecto. Espero que esto te ayudará.
- ¿Cómo decirle a Gradle que use un diferente AndroidManifest desde la línea de comandos?
- Falta la imagen de api nivel 15 en el estudio android