Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

android - press "." many times (validate ip address in EditText while typing)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...