关于实现Android EditText实现IP地址简单实现,通过设置Editext输入监听接口,在每次输入字符完成之后,整体处理, 对输入限制做了如下处理:每段无法输入0开始数字,“.”字符无法做首字符,输入限制4段。
mEtIPAddress.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
afterText(s);
}
});
}
private boolean isDot = false;
private void afterText(Editable s) {
String ip = s.toString();
Log.d(TAG, "afterText: "+s);
if (ip.startsWith(".")) {
// ip地址首位“.”排除
s.replace(0,1,"");
return;
}
String[] ipArr = ip.split("\\.");
// 处理多余的段数
if(ipArr.length==4 && 46 == ip.charAt(ip.length()-1)) {
s.delete(ip.length()-1, ip.length());
}
// 处理重复的“.”
if (!"".equals(ip)&& 46 == ip.charAt(ip.length()-1)) {
if (!isDot) {
isDot = true;
} else {
isDot = false;
s.delete(ip.length()-1, ip.length());
}
return;
}
isDot = false;
int off = 0;
// 处理每段范围
for (String value : ipArr) {
int len = ip.length();
if ("".equals(value)) {
s.delete(off, ip.length());
}
if (len > 0 && value.startsWith("0")) {
s.replace(off, off + 1, "");
}
if (!"".equals(value) && Integer.parseInt(value) > 255) {
// ip最大255
s.delete(off, ip.length());
s.append("255");
}
off += value.length();
off++;
}
}
<EditText
android:id="@+id/et_ip_address"
android:background="@android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textSize="20sp"
android:digits="0123456789."
android:maxLength="15"
android:visibility="visible"
android:inputType="number"
android:hint="0.0.0.0"/>