What android:inputType should I use for entering an IP Address and hostname?

46,530

Solution 1

Try using android:inputType="number", but also set android:digits="0123456789.". Works for me.

Solution 2

If you use inputType="phone" you gain access to a cut down keyboard containing Numbers and a Period character - this doesn't restrict the input with regards to the amount of Periods you can enter.

Please see this answer for validation while being entered.

Solution 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"/>

Solution 4

You can use your own input filter for that

final EditText text = new EditText(ServerSettings.this);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
    @Override
    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);

Solution 5

use this :

<EditText
    android:id="@+id/txtIP"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789."
 />
Share:
46,530
AngryHacker
Author by

AngryHacker

Updated on March 09, 2021

Comments

  • AngryHacker
    AngryHacker about 3 years

    I am building a small Android app where the user will enter an IP address or a hostname into an EditText widget. 90% of the time they will be entering an IP address, the rest of the time - a hostname.

    So naturally, I want to make it easy for them to enter an IP address, but the ability to switch to alpha numerics for hostname entry is important.

    I can't seem to find a good inputType. The numberDecimal initially seemed like a good shot, but it only allows one dot.

    Ideally, I'd like to start with a standard keyboard that had the ?123 button pressed.

    How do I get there?