Android 如果edittext中填充了输入,是否更改其下划线颜色?
如果edittext中填充了输入,是否更改其下划线颜色 声明:Android 如果edittext中填充了输入,是否更改其下划线颜色?,android,kotlin,android-edittext,Android,Kotlin,Android Edittext,如果edittext中填充了输入,是否更改其下划线颜色 声明: 未聚焦:颜色/1 聚焦:彩色/2 未聚焦(输入后):颜色/2 我尝试使用: edtText.doAfterTextChanged { } 但是,我在doAfterTextChanged中找不到attribute“edtText.backgroundTint”您可以使用TextWatcher进行此操作,并使用setbackgroundtinlist更改线条颜色 et.addTextChangedListener(new Text
edtText.doAfterTextChanged {
}
但是,我在doAfterTextChanged中找不到attribute“edtText.backgroundTint”您可以使用
TextWatcher
进行此操作,并使用setbackgroundtinlist
更改线条颜色
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && !(s.toString().isEmpty())) {
//Color when text exists
ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.colorPrimaryDark));
ViewCompat.setBackgroundTintList(et, colorStateList);
} else {
//Default color - color when text does not exist
ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.colorAccent));
ViewCompat.setBackgroundTintList(et, colorStateList);
}
}
@Override
public void afterTextChanged(Editable s) {}
});
请参考此项。您可以首先将a用于EditText
backgroundTint
属性,该属性在聚焦与否时选择正确的颜色
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/focused" android:state_focused="true" />
<item android:color="@color/unfocused" android:state_focused="false" />
</selector>
对所有其他
EditText
视图重复相同的操作。它很好用。代码有问题吗?是的,它改变了整个背景而不是下划线。这不会发生。您可以使用setColorFilteryeah实现这一点,如果我们不向editText添加自定义xml背景,它就可以工作了。谢谢,先生,我在后文本更改中填充代码。但是,getResource().getColor()不推荐使用。因此,我使用ContextCompat.getColor(),我认为在onTextChanged
中使用它会更好。因为这样,一旦用户开始输入,颜色就会改变。但这完全取决于他的用例。
<EditText
android:id="@+id/edit_text1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:backgroundTint="@drawable/selector" />
EditText editText1 = findViewById(R.id.edit_text1);
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.isEmpty(editText1.getText().toString()))
editText1.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.focused));
else
editText1.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.unfocused));
}
});