如果用输入填充了edittext,则更改其下划线颜色吗?
状态:
我尝试使用:
edtText.doAfterTextChanged {
}
但是,我在doAfterTextChanged中找不到属性“ edtText.backgroundTint”
答案 0 :(得分:3)
您可以为此使用TextWatcher
和setBackgroundTintList
来更改线条颜色,
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) {}
});
请参阅此link。
答案 1 :(得分:1)
最初,您可以为EditText
backgroundTint
属性使用selector,该属性可以在焦点对准或不聚焦时选择合适的颜色
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
android:id="@+id/edit_text1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:backgroundTint="@drawable/selector" />
在更改文本时,请使用TextUtils.isEmpty()
检查文本是否为空,并相应地更改颜色:
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));
}
});
对所有其他EditText
视图重复相同的操作