2013-05-09 38 views
0

我有一個場景像下面的圖片:在android中進行EditText驗證?

enter image description here

如果用戶不寫用戶名或電子郵件字段任何東西,它會顯示問號。另一方面它會顯示十字標記。如何實現它?

+0

你想清除所有並驗證嗎? – 2013-05-09 09:20:02

+0

爲清除所有你需要創建自定義controll – 2013-05-09 09:21:26

+0

不,我不想清除所有,但我想玩單場。 – androidcodehunter 2013-05-09 09:21:55

回答

1
etUsername.addTextChangedListener(mTextWatcher); 

etUsername.setOnTouchListener(new MyOnTouchListener(etUsername)); 

TextWatcher:顯示或由用戶輸入隱藏清除按鈕

private TextWatcher mTextWatcher = new TextWatcher() { 

    boolean isnull = true; 

    @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(s)){ 
      if(!isnull){ 
       etUsername.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); 
       isnull = true; 
      } 
     }else{ 
      if(isnull){ 
       etUsername.setCompoundDrawablesWithIntrinsicBounds(null, null, mClearIcon, null); 
       isnull = false; 
      } 
     } 
    } 

MyOnTouchListener:Clear按鈕點擊收聽

class MyOnTouchListener implements OnTouchListener{ 

    EditText mEditText; 

    public MyOnTouchListener(EditText editText){ 
     this.mEditText = editText; 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     switch(event.getAction()){ 
     case MotionEvent.ACTION_UP: 
      int curX = (int)event.getX(); 
      if(curX > v.getWidth() - 60 
        && !TextUtils.isEmpty(mEditText.getText())){ 
    // the clear button was clicked,do something you need 
    // for example, show the hint msg,etc 
       return true; 
      } 
      break; 
     } 
     return false; 
    } 

您可以使用代碼上面做一個自定義視圖

+0

如何獲取mClearIcon資源。請幫幫我。 – androidcodehunter 2013-05-09 09:50:23

+0

查看'setCompoundDrawablesWithIntrinsicBounds'方法,'mClearIcon'是'Drawable' – tesla1984 2013-05-09 10:14:40

+0

工作很好,謝謝你的幫助。 – androidcodehunter 2013-05-09 11:12:54