Android APP開發活用範例速查大辭典(Ch0119-EditText限制輸入文字)
GUI-XML片段
<EditText android:id=”@+id/restriction” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:hint=”只允許輸入電子郵件地址” android:textSize=”16sp” />
|
程式碼片段
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ch0119_main); final EditText et = (EditText) findViewById(R.id.restriction);
// 建立電子郵件位址用的Filter InputFilter inputFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source.toString().matches(“^[0-9a-zA-Z@\\.\\_\\-]+$”)) { return source; } else { return “”; } } };
// //將Filter加入陣列 InputFilter[] filters = new InputFilter[] { inputFilter }; // 套用Filter et.setFilters(filters);
}
|