按“."多次(键入时在 EditText 中验证 IP 地址

press quot;.quot; many times (validate ip address in EditText while typing)(按“.多次(键入时在 EditText 中验证 IP 地址))

本文介绍了按“."多次(键入时在 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 地址

基础教程推荐