Android 通过 Java 激活和不激活时更改 EditText 重音的颜色

Android Change Color of EditText Accent via Java When Active & Not Active

我一直在使用从另一个问题得到的下面的代码分成两行以编程方式编辑颜色。

((EditText) row1.getVirtualChildAt(i))

下面的代码是我在上面一行之后用来改变颜色的代码。

.getBackground().mutate().setColorFilter(getResources().getColor(R.color.Green), PorterDuff.Mode.SRC_ATOP);

现在它设置下划线颜色,因此无论是否使用 EditText 框,下划线颜色始终为绿色。

我如何设置它,以便在我点击离开 EditText 框后它恢复到默认颜色。我也可以指定另一种颜色作为默认颜色,例如浅灰色。

您可以使用 OnFocusChangeListener.java 注册您的编辑文本,并且在焦点更改时您可以更改颜色。

void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
// color while typing
}else{
// color when clicked away
}

}

您可以为要在 res/color/your_edittext_color_state.xml 文件夹中添加的不同编辑文本状态创建颜色选择器 xml。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#YOUR_COLOR"/>
    <item android:state_focused="true" android:color="#ANY_COLOR"/>
    <item android:color="#DEFAULT_COLOR"/>
</selector>

然后你可以在你的代码中设置 foregroundTint

editText.setForegroundTintList(getApplicationContext().getResources().getColorStateList(R.color.your_edittext_color_state));

我最终遵循了此处给出的答案: How do I create ColorStateList programmatically?

我确实改变了一些东西,因为顺序很重要,我花了一些时间才意识到这一点。

将下面的代码块放在 MainActivity 的开头。

int[][] states = new int[][] {
        new int[] { android.R.attr.state_focused}, // enabled
        //new int[] {-android.R.attr.state_enabled}, // disabled
        //new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_window_focused}  // pressed
};

int[] colors = new int[] {
        Color.GREEN,
        //Color.BLUE,
        //Color.YELLOW,
        Color.GRAY
};

ColorStateList myColorAccentList = new ColorStateList(states, colors);

然后将我的语句放在我的 for 循环中需要它的地方。

((EditText) row1.getVirtualChildAt(i)).setBackgroundTintList(myColorAccentList);

对于其他人,您可能只想在编辑文本的末尾添加这一部分。

.setBackgroundTintList(myColorAccentList);