android IP输入框
本文提供一种IP输入框的实现方法,会过滤非IP字符的输入,同时过滤非法IP的输入,同时提供确定和取消事件的处理接口。具体实现如下:
[java]
private static String tmp = "";
// IP 输入框
public static void showIPInputDialog(final Context context, final String title, final String initIp, final onIPInputDialogProcess listener){
tmp = "";
final EditText ip = new EditText(context);
ip.setText(initIp);
ip.setInputType( InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_TEXT );
ip.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
String str = s.toString();
if( str.length() == 0 || str.equals(tmp)) return;
tmp = checkIp(str);
ip.setText(tmp);
ip.setSelection(tmp.length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}});
new AlertDialog.Builder(context)
.setTitle(title)
.setView(ip)
.setPositiveButton(R.string.dialog_bt_ok, new OnClickListener(){
public void onClick(DialogInte易做图ce dialog, int which) {
String ipText = ip.getText().toString();
if( ipText.split("\\.").length == 4 ){
if( listener != null ) listener.onIPInputConfirm(ip.getText().toString());
}else{
showIPInputDialog(context, title, ipText, listener);
}
}})
.setNegativeButton(R.string.dialog_bt_cancel, new OnClickListener(){
public void onClick(DialogInte易做图ce dialog, int which) {
if( listener != null ) listener.onIPInputCancel();
}})
.show();
}
private static String checkIp(String ip){
String validStr = ".0123456789";
StringBuffer sb = new StringBuffer();
int i = 0;
for( i = 0; i < ip.length(); i++){
if( validStr.indexOf(ip.charAt(i)) >= 0 ) sb.append(ip.charAt(i));
}
if( sb.toString().length() == 0 ) return "";
String newIP = "";
String[] arrIp = sb.toString().split("\\.");
for( i = 0; i < arrIp.length && i < 4 ; i++){
if( arrIp.equals("")) break;
if( i > 0 && i < 4 ) newIP += ".";
if( Integer.parseInt(arrIp[i]) > 255 ){
newIP += String.format("%d", Integer.parseInt(arrIp[i])/10);
}else{
newIP += arrIp[i];
}
}
if( i < 4 && sb.toString().endsWith("-")) newIP += ".";
return newIP;
}
inte易做图ce onIPInputDialogProcess{
void onIPInputConfirm(String ip);
void onIPInputCancel();
}
补充:移动开发 , Android ,