问题描述
我有以下 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 地址)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)