当我们想实时控制用户的输入,将用户的输入的字符长度限制在一个范围内,我们可以写如下的一个字符长度限制类:
import android.text.InputFilter;
public class MaxTextLengthUtils implements InputFilter {
private int mMaxLength;
private Context contxt;
private ImageView deleteBtn;
public MaxTextLengthUtils(int max , Context context, ImageView imageView) {
mMaxLength = max;
contxt = context;
deleteBtn = imageView;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
int keep = mMaxLength - (dest.length() - (dend - dstart));
if (keep < (end - start)) {
Toast.makeText(contxt, "不得超过" + max + "个字符", Toast.LENGTH_LONG).show();
}
if (source.length() == 0 && (dest.length() - (dend - dstart)) == 0) {
deleteBtn.setVisibility(View.GONE);
}
if (keep <= 0) {
retun "";
} else if (keep >= end - start) {
return null;
} else {
return source.subSequence(start, start + keep);
}
}
}
EditText input = (EditText) inflateLayout.findViewById(R.id.xxx);
ImageView deleteButton = (ImageView) inflateLayout.findViewById(R.id.xx);
input.setFilters(new InputFilter[]{new MaxTextLengthUtils(30, xxxActivity.this, deleteBtn)});
|