問(wèn)題描述
我有以下 EditText:
I have the following EditText:
<EditText
android:id="@+id/ip"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal">
</EditText>
我想用它來(lái)獲取IP地址.但它不允許我輸入."(句號(hào))不止一次,因?yàn)?inputtype 設(shè)置為 numberDecimal.關(guān)于如何獲得多個(gè)."的任何建議同時(shí)將 inputType 設(shè)置為數(shù)字.
I want to use this to get ip address. But it will not allow me to type '.' (period sign) more than once because the inputtype is set to numberDecimal. Any suggestion on how to get more than one '.' while setting inputType to numbers.
推薦答案
你需要?jiǎng)?chuàng)建自己的InputFilter
:http://developer.android.com/reference/android/text/InputFilter.html
看看我前段時(shí)間寫(xiě)的這個(gè)答案:如何設(shè)置 Edittext 視圖只允許兩個(gè)數(shù)值和兩個(gè)十進(jìn)制值,如 ##.##
Take a look at this answer I wrote some time ago: How to set Edittext view allow only two numeric values and two decimal values like ##.##
這是對(duì)該過(guò)濾器的修改以驗(yàn)證 ips.它檢查是否存在四位數(shù)字,用點(diǎn)分隔,并且沒(méi)有一個(gè)大于 255.驗(yàn)證是實(shí)時(shí)進(jìn)行的,即在打字時(shí).
Here is an adaptation to that filter to validate ips. It checks for the presence of four digits, separated by dots and none of them bigger than 255. The validation occurs in real time, i.e., while typing.
EditText text = new EditText(this);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
if (!resultingTxt.matches ("^\d{1,3}(\.(\d{1,3}(\.(\d{1,3}(\.(\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\.");
for (int i=0; i<splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
return "";
}
}
}
}
return null;
}
};
text.setFilters(filters);
這篇關(guān)于按“."多次(鍵入時(shí)在 EditText 中驗(yàn)證 IP 地址)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!