press quot;.quot; many times (validate ip address in EditText while typing)(按“.多次(键入时在 EditText 中验证 IP 地址))
问题描述
我有以下 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 设置为 numberDecimal.关于如何获得多个."的任何建议同时将 inputType 设置为数字.
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.
推荐答案
你需要创建自己的InputFilter:http://developer.android.com/reference/android/text/InputFilter.html
看看我前段时间写的这个答案:如何设置 Edittext 视图只允许两个数值和两个十进制值,如 ##.##
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.它检查是否存在四位数字,用点分隔,并且没有一个大于 255.验证是实时进行的,即在打字时.
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);
这篇关于按“."多次(键入时在 EditText 中验证 IP 地址)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按“."多次(键入时在 EditText 中验证 IP 地址
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
