2012-11-12 46 views
1

我已經實現一個簡單的驗證用於文本編輯.setError(),使用此代碼:機器人:驗證的EditText與TextWatcher和

title = (EditText) findViewById(R.id.title); 
    title.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable s) { 
      if (title.getText().length() < 1) { 
        title.setError("Title is required"); 
       } else { 
        title.setError(null); 
       } 

     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 
      // TODO Auto-generated method stub 

     } 
    }); 

的funcion檢查,如果有插入上的textchange和一切任何文本完美的作品,除非我把光標放在已經是空的標題字段中,然後再按一次刪除。錯誤信息被重新設置,並且不會調用textwatcher,因爲沒有文本更改。我怎麼能在這種情況下顯示錯誤信息?

+0

正在調用文本監視器。但是,在已經是空的文本字段中,如果您點擊刪除鍵,請注意沒有文本更改,因此afterTextChanged不會被調用。 –

+0

找到解決方案!請參閱下面的答案。 –

回答

0

您應該也可以覆蓋onKeyUp方法(http://developer.android.com/reference/android/view/KeyEvent.Callback.html)。在那裏,檢查按下的鍵是否爲KeyEvent.KEYCODE_DEL,然後檢查EditText中的文本是否爲空。如果是,請拋出錯誤。

+1

好的建議,但KeyEvents不鼓勵軟輸入。 「不能保證在軟鍵盤上的任何按鍵都會產生關鍵事件,這由IME自行決定,默認的軟件鍵盤將永遠不會向任何針對Jelly Bean或更高版本的應用程序發送任何關鍵事件,並且只會發送事件的一些按刪除和返回鍵的應用程序目標冰淇淋三明治或更早的「 http://developer.android.com/reference/android/view/KeyEvent.html –

+0

有趣的是,我沒有看到。如果是這樣,我不完全確定OP能夠完成他們想要的。 –

+0

太糟糕了,但謝謝你的嘗試!我放棄了,只是實施了一個簡單的檢查提交... –

0

看起來內部TextView有一個標誌,如果鍵盤發送一個鍵盤命令但文本保持不變,則調用setError(null)。所以我分類EditText和實施onKeyPreIme()吞下刪除鍵,如果文本是「」。只需在您的XML文件中使用EditTextErrorFixed即可:

package android.widget; 

import android.content.Context; 
import android.text.TextUtils; 
import android.util.AttributeSet; 
import android.view.KeyEvent; 

public class EditTextErrorFixed extends EditText { 
    public EditTextErrorFixed(Context context) { 
     super(context); 
    } 

    public EditTextErrorFixed(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public EditTextErrorFixed(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    /** 
    * Don't send delete key so edit text doesn't capture it and close error 
    */ 
    @Override 
    public boolean onKeyPreIme(int keyCode, KeyEvent event) { 
     if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL) 
      return true; 
     else 
      return super.onKeyPreIme(keyCode, event); 
    } 
}