Android实战简易教程-第七十枪(自定义实用控制之-邮箱验证EditText)
投稿于 被查看 17104 次 评论:211
Android实战简易教程-第七十枪(自定义实用控制之-邮箱验证EditText)
我们自定义一款可以验证用户输入邮箱是否符合规范的EditText.
1.布局文件:
2.自定义控件:
package com.example.drawableedittext; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; public class DrawableEditText extends RelativeLayout { private Context mContext; private EditText mEditText; private ImageView mImage; public DrawableEditText(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; init(); // 设置文字大小 int textSize = attrs.getAttributeResourceValue(null, textSize, 0); if (textSize != 0) { mEditText.setTextSize(textSize); } // 设置edittext的hint提示 int hint = attrs.getAttributeResourceValue(null, hint, 0); if (hint != 0) { mEditText.setHint(hint); } // 设置文本颜色 int textColor = attrs.getAttributeResourceValue(null, textColor, 0); if (textColor != 0) { mEditText.setTextColor(textColor); } } // 初始化布局和控件 public void init() { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.drawable_edittext, this); mEditText = (EditText) view.findViewById(R.id.edittext); mImage = (ImageView) view.findViewById(R.id.image); } // 根据文本框是否为空设置不同的图片 private void setDrawable() { if (checkEmail(mEditText.getText().toString())) { mImage.setImageResource(R.drawable.right); //mImage.setImageResource(nullImgRes); } else { //mImage.setImageResource(imgRes); mImage.setImageResource(R.drawable.close); } } @Override protected void onFinishInflate() { super.onFinishInflate(); // 文本框的text改变监听 mEditText.addTextChangedListener(new TextWatcher() { @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) { setDrawable(); } }); } /** * 验证邮箱 * * @param email * @return */ public static boolean checkEmail(String email) { boolean flag = false; try { String check = ^([a-z0-9A-Z]+[-|_|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); flag = matcher.matches(); } catch (Exception e) { flag = false; } return flag; } }
3.引入控件:
运行实例:
用户评论