android edittext 文本过滤,android – EditText和InputFilter会导致重复的文本

我试图实现一个限制输入到alpha字符[A-Za-z]的EditText.

我从this post开始使用InputFilter方法.当我输入“a%”时,文本消失,如果我退回空格,文本是“a”.我已经尝试过滤器功能上的其他变体,如使用正则表达式仅匹配[A-Za-z],有时会看到像重复字符一样的疯狂行为,我将键入“a”然后键入“b”,然后获取“aab”键入“c”并得到“aabaabc”然后命中空格并获得“aabaabcaabaabc”!

这是我正在使用的代码与我尝试过的不同的方法.

EditText input = (EditText)findViewById( R.id.inputText );

InputFilter filter = new InputFilter() {

@Override

public CharSequence filter( CharSequence source,int start,int end,Spanned dest,int dstart,int dend ) {

//String data = source.toString();

//String ret = null;

/*

boolean isValid = data.matches( "[A-Za-z]" );

if( isValid ) {

ret = null;

}

else {

ret = data.replaceAll( "[@#$%^&*]","" );

}

*/

/*

dest = new SpannableStringBuilder();

ret = data.replaceAll( "[@#$%^&*]","" );

return ret;

*/

for( int i = start; i < end; i++ ) {

if( !Character.isLetter( source.charAt( i ) ) ) {

return "";

}

}

return null;

}

};

input.setFilters( new InputFilter[]{ filter } );

我完全忍不住在这一个,所以任何帮助在这里将不胜感激.

编辑:

好的,我已经对InputFilter进行了很多实验,并得出了一些结论,尽管没有解决问题.请参阅我的代码中的注释.我现在要尝试Imran Rana的解决方案.

EditText input = (EditText)findViewById( R.id.inputText );

InputFilter filter = new InputFilter() {

// It is not clear what this function should return!

// Docs say return null to allow the new char(s) and return "" to disallow

// but the behavior when returning "" is inconsistent.

//

// The source parameter is a SpannableStringBuilder if 1 char is entered but it

// equals the whole string from the EditText.

// If more than one char is entered (as is the case with some keyboards that auto insert

// a space after certain chars) then the source param is a CharSequence and equals only

// the new chars.

@Override

public CharSequence filter( CharSequence source,int dend ) {

String data = source.toString().substring( start,end );

String retData = null;

boolean isValid = data.matches( "[A-Za-z]+" );

if( !isValid ) {

if( source instanceof SpannableStringBuilder ) {

// This works until the next char is evaluated then you get repeats

// (Enter "a" then "^" gives "a". Then enter "b" gives "aab")

retData = data.replaceAll( "[@#$%^&*']","" );

// If I instead always returns an empty string here then the EditText is blanked.

// (Enter "a" then "^" gives "")

//retData = "";

}

else { // source is instanceof CharSequence

// We only get here if more than 1 char was entered (like "& ").

// And again,this works until the next char is evaluated then you get repeats

// (Enter "a" then "& " gives "a". Then enter "b" gives "aab")

retData = "";

}

}

return retData;

}

};

input.setFilters( new InputFilter[]{ filter } );

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值