[英]Android: Validation symbol in EditText
如果EditText的驗證返回false,我們有setError
方法用於在框的末尾設置帶有紅色感嘆號的錯誤消息:
我想設置一個綠色刻度符號 ,就像我的驗證返回true時盒子末尾的紅色感嘆號一樣:
password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (password.getText().toString().length() < 6) {
password.setError("Password should be greater than 6 characters!");
}
else {
//validation is true, so what to put here?
}
}
}
});
}
編輯1看似不可能,但問題還有更多。 我這樣做了:
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String mail = email.getText().toString();
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(mail).matches()) {
email.setError("Please enter a valid email address");
}
else {
Log.i("yay!","Email is valid!!!");
email.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.validated, 0);
}
}
}
});
雖然我可以在我的日志中看到yay: Email is valid!!!
,我無法在EditText
的末尾看到驗證符號。
但是,令我驚訝的是,當我將if
語句更改為始終為false
,我可以看到帶有log語句的符號。
有關為什么會發生這種情況的任何解釋?
驗證為true時,您可以顯示drawableRight
。
password.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.rightImage, 0);
驗證為false時將其設置恢復正常。
password.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
我剛剛使用setError(CharSequence error, Drawable icon)
在我自己的項目中測試了它
獲取一個新圖標:
轉到我的drawable文件夾
添加新的矢量資產。
我選擇了“素材圖標”並瀏覽,
然后選擇了ic_done_24pp。
顏色:
接下來,我進入xml並通過更改fillcolor使其變為綠色:
android:fillColor="#FF00FF00"
3:更改代碼:
Drawable myIcon = getResources().getDrawable(R.drawable.ic_done_24dp);
myIcon.setBounds(0, 0, myIcon.getIntrinsicWidth(), myIcon.getIntrinsicHeight());
mPasswordView.setError("Good", myIcon);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.