preSS""很多次(验证IP地址的EditText同时打字)很多次、地址、QUOT、preSS

2023-09-13 00:56:12 作者:梨花雨凉

我有以下的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.

推荐答案

您需要创建自己的输入过滤:http://developer.android.com/reference/android/text/InputFilter.html

看看这个答案我前段时间写的:How设置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。它检查了presence的四位数字,由点及他们都不大于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);