Here is my EditText and want to make it to accept only a IP address. I used numberDecimal as inputType but its not accepting more than one point.
<EditText
android:id="@+id/etBannedIpAddress"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="IP Address"
android:inputType="numberDecimal"
android:textAppearance="@android:style/TextAppearance.Small"
android:textColor="@color/blue_text" />
try like this: by using input filter we can filter the data before entering the value only.
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.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;
}
};
editTxxt.setFilters(filters);
Approach 1: Using input filter, Try below code:
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);
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.
But you need to write a custom input filter code like above.
Approach 2: Add android:inputType="number|numberDecimal"
and android:digits="0123456789."
<EditText
android:id="@+id/ip_address"
android:inputType="number|numberDecimal"
android:digits="0123456789."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With