問題描述
我有以下 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>
我想用它來獲取IP地址.但它不允許我輸入."(句號)不止一次,因為 inputtype 設(shè)置為 numberDecimal.關(guān)于如何獲得多個."的任何建議同時將 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.
推薦答案
你需要創(chuàng)建自己的InputFilter
:http://developer.android.com/reference/android/text/InputFilter.html
看看我前段時間寫的這個答案:如何設(shè)置 Edittext 視圖只允許兩個數(shù)值和兩個十進(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 ##.##
這是對該過濾器的修改以驗證 ips.它檢查是否存在四位數(shù)字,用點分隔,并且沒有一個大于 255.驗證是實時進(jìn)行的,即在打字時.
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)于按“."多次(鍵入時在 EditText 中驗證 IP 地址)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!