如何在用户暂停/离开编辑文本区域时检查验证

时间:2015-12-02 07:33:50

标签: android

这里我描述了用户离开edittext焦点时的检查验证代码......

    TextWatcher tw = 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) {
           // Check Condition

            } else {

//检查条件

            }
        }

        @Override
        public void afterTextChanged(Editable s) { }
    };

    // text watcher registration to the 2 EditText
    etEmail.addTextChangedListener(tw);
    etPassword.addTextChangedListener(tw);
    etUserName.addTextChangedListener(tw);

2 个答案:

答案 0 :(得分:1)

您可以在活动的onCreate方法内的EditText上注册OnFocusChangeListener:

final EditText et = (EditText)findViewById(R.id.my_edit_text);
  et.setOnFocusChangeListener(new View.OnFocusChangeListener()
  {
  @Override
  public void onFocusChange(View v, boolean hasFocus)
  {
    if (!hasFocus)
        // TODO: the editText has just been left
  }
});

这里onFocusChange的v参数是你的EditText控件。

答案 1 :(得分:0)

这是一个例子,

edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus){
        Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
    }else {
        Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
    }
   }
});