android 输入光标修改颜色_Android-EditText之代码动态修改编辑框光标颜色(通过反射的方式-简单记录下)...

这篇博客介绍了如何通过反射方式动态修改Android中EditText的输入光标颜色。提供了编辑框工具类`EditTextUtil`的实现代码,以及在实际使用中如何调用该工具类设置光标颜色的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近再做通用弹窗的封装FanChael/CommonPopupWindow,在涉及到注册、登录弹窗的时候,为了统一色调(光标、下划线、按钮),用户调用时会传入颜色“#xxxxxxx”,这个时候就需要修改:

1. 光标的颜色

2. 编辑框下划线的颜色(通过app模块下的style主题下增加control配色即可EditText下划线颜色修改 - 君子剑的博客 - CSDN博客)

3. 按钮的颜色统一,由于用到了shape样式,所以就需要代码动态创建shape并进行按钮Button或者TextView的背景设置 MonkeyLei:Android-代码动态创建Shape并运用到控件背景(GradientDrawable)

所以就差光标颜色了,直接反射搞!

1. 工具类

import android.graphics.PorterDuff;

import android.graphics.drawable.Drawable;

import android.widget.EditText;

import android.widget.TextView;

import java.lang.reflect.Field;

/*

*@Description: 编辑框工具类

*@Author: hl

*@Time: 2019/2/20 9:29

*/

public class EditTextUtil {

/**

* 代码设置光标颜色

*

* @param editText 你使用的EditText

* @param color 光标颜色

*/

public static void setCursorDrawableColor(EditText editText, int color) {

try {

Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");//获取这个字段

fCursorDrawableRes.setAccessible(true);//代表这个字段、方法等等可以被访问

int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);

Field fEditor = TextView.class.getDeclaredField("mEditor");

fEditor.setAccessible(true);

Object editor = fEditor.get(editText);

Class> clazz = editor.getClass();

Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");

fCursorDrawable.setAccessible(true);

Drawable[] drawables = new Drawable[2];

drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);

drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);

drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);//SRC_IN 上下层都显示。下层居上显示。

drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);

fCursorDrawable.set(editor, drawables);

} catch (Throwable ignored) {

}

}

}

2. 使用(TextInputEditText/EditText)

///< 编辑框下划线颜色、按钮颜色统一修改

EditTextUtil.setCursorDrawableColor(usernameEt, Color.parseColor("#f0008DCF"));

EditTextUtil.setCursorDrawableColor(verifypassEt, Color.parseColor("#f0008DCF"));

简单记录下,封装弹窗还是需要一些知识哒....小白的路还长....

据说失效了,来补充一波,搞个style设置到Edittext,建议提出一个公共的控件继承Edittext,然后统一设置,其他地方用这个简单自定义控件即可 - 貌似有其他方式可以!

@color/gray_d

@color/green_all_bg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值