栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Android中以编程方式更改Edittext光标颜色?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Android中以编程方式更改Edittext光标颜色?

使用一些反射对我有用

Java:

// https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564Field 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>

您可以使用不需要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) {  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号