press “.” many times (validate ip address in EditT

2019-01-18 17:20发布

问题:

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>

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.

回答1:

You need to create your own InputFilter: http://developer.android.com/reference/android/text/InputFilter.html

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 ##.##


Update - sample code

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);


回答2:

Found this solution on another thread.

You should use the att:

android:digits="0123456789."

http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits



回答3:

This works perfectly keyboard with numbers and decimal by adding android:inputType="number|numberDecimal" and android:digits="0123456789."

Example

 <EditText
    android:id="@+id/ip_address"
    android:inputType="number|numberDecimal"
    android:digits="0123456789."
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>