更改edittext的下划线颜色(如果输入充满)?

时间:2020-03-19 18:46:06

标签: android kotlin android-edittext

如果用输入填充了edittext,则更改其下划线颜色吗?

enter image description here

状态:

  1. 未聚焦:颜色/ 1
  2. 聚焦:颜色/ 2
  3. 未聚焦(输入后):颜色/ 2

我尝试使用:

edtText.doAfterTextChanged {

}

但是,我在doAfterTextChanged中找不到属性“ edtText.backgroundTint”

2 个答案:

答案 0 :(得分:3)

您可以为此使用TextWatchersetBackgroundTintList来更改线条颜色,

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视图重复相同的操作