TextWatcher也是不錯的選擇,但我更喜歡使用自定義過濾器。 因此,簡單的方法是使用輸入過濾器,並採取對飛每一個字符的控制,看下面的例子,希望這有助於
import android.text.InputFilter;
import android.text.InputType;
EditText input_moodMsg;
// initialize this edittext etc etc
//....
// here comes the filter to control input on that component
InputFilter inputFilter_moodMsg = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {
if (source.length()>44) return "";// max 44chars
// Here you can add more controls, e.g. allow only hex chars etc
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i)) && !Character.isSpaceChar(source.charAt(i))
&& source.charAt(i)!='-'
&& source.charAt(i)!='.'
&& source.charAt(i)!='!'
) {
return "";
}
}
return null;
}
};
input_moodMsg.setFilters(new InputFilter[] { inputFilter_moodMsg });
input_moodMsg.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
用戶setInputType()屬性的EditText .. –