运行效果图
布局文件activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Email格式的检测" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/etInfo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:ems="10"
android:hint="请输入Email"/>
<ImageView
android:id="@+id/IvShow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"/>
</LinearLayout>
</LinearLayout>
修改MainActivity.java
需要两个图片来显示验证是否通过,wrong_bg.png和right_bg.png
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.text.method.KeyListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
private EditText etInfo=null;//输入框
private ImageView IvShow=null;//判断显示图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findById();
setLisitener();//设置视图的监听对象
}
private void setLisitener() {
//设置输入框组件绑定的监听事件
etInfo.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
switch (event.getAction()) {//得到操作类型
case KeyEvent.ACTION_DOWN://键盘按下
String inputString=etInfo.getText().toString();//获取输入框中的额内容
if(inputString.matches("\\w+@\\w+\\.\\w+")){//利用正则表达式进行验证
IvShow.setImageResource(R.drawable.right_bg);//通过
}else{
IvShow.setImageResource(R.drawable.wrong_bg);//不通过
}
break;
case KeyEvent.ACTION_UP://键盘弹起
break;
}
return false;
}
});
}
private void findById() {
etInfo=(EditText) findViewById(R.id.etInfo);
IvShow=(ImageView) findViewById(R.id.IvShow);
}
}