package com.oocl.filter;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class InputFilterTestActivity extends Activity {
/** Called when the activity is first created. */
private TextView myText;
private EditText myEdit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String str = "Longfu2012";
setContentView(R.layout.main);
myText = (TextView) findViewById(R.id.myText);
myText.setText("输入后面字符:"+str);
myEdit = (EditText) findViewById(R.id.myEdit);
myEdit.setFilters(new InputFilter[] { new MyFilter(str) });
}
public class MyFilter implements InputFilter {
String ch = null;
String str = null;
public MyFilter(String str) {
this.str = str;
}
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
//最后输入的一个字符
if (dest.length() < str.length()) {
//截取未过滤的最后一个字符
ch = str.substring(dstart + start, dstart + end);
} else {
return dest.subSequence(dstart, dend);
}
if (ch.equals(source)) {
Toast.makeText(InputFilterTestActivity.this, "符合要求",
Toast.LENGTH_SHORT).show();
//符合规定要求的字符以原输入显示
return dest.subSequence(dstart, dend) + source.toString();
} else {
Toast.makeText(InputFilterTestActivity.this, "不符合要求喔~",
Toast.LENGTH_SHORT).show();
//如果没有按要求输入字符,则该字符被“*”代替,并显示
return dest.subSequence(dstart, dend) + "*";
}
}
}
}