简体   繁体   中英

EditText validation in android?

I have a scenario like the image below:

在此处输入图片说明

If a user don't write anything in Username or Email field, it will show question mark. On the other hand it will show cross mark. How to achieve it???

etUsername.addTextChangedListener(mTextWatcher);

etUsername.setOnTouchListener(new MyOnTouchListener(etUsername));

TextWatcher :show or hide the clear button by the user's input

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 :the clear button click listener

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;
    }

you can use the code above to make a custom view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM