gpt4 book ai didi

java - 在没有 xml 的情况下更改 edittext 光标颜色和大小?

转载 作者:行者123 更新时间:2023-12-02 02:25:00 25 4
gpt4 key购买 nike

我一直在开发一个练习应用程序,用户可以在其中设置文本和背景的颜色。但我没能找到解决办法

android:textCursorDrawable="@null"

我已经尝试过这个,虽然它将颜色设置为与文本颜色相同,但这不是我想要做的,因为我为光标设置了特定的大小。

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="10dip" />
<size android:height="14dip" />
<solid android:color="#fff" />
</shape>

我也尝试过 android:color="@null"但没有返回任何内容......显然是真的(这是我自己的愚蠢的一个注释)。

终于看到这个了。

 Field f = null;
f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(editText, R.drawable.cursor);

我可以通过这种方式设置颜色吗?或者它只是我已有的 xml 调用的 java 版本?任何帮助将不胜感激。

总的来说,我想将光标的颜色设置为与编辑文本颜色相同,但光标的高度和宽度为 10x14?

谢谢

最佳答案

请检查光标颜色变化,

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) {
}
}

关于java - 在没有 xml 的情况下更改 edittext 光标颜色和大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47920588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com