This article provides an IP address input box that filters out non-IP character input, filters out illegal IP address input, and provides an interface for determining and canceling events. The specific implementation is as follows:
[Java]
Private static String tmp = "";
// IP input box
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 (DialogInterface 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 (DialogInterface 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]) & gt; 255 ){
NewIP + = String. format ("% d", Integer. parseInt (arrIp [I])/10 );
} Else {
NewIP + = arrIp [I];
}
}
If (I <4 & sb. toString (). endsWith ("-") newIP + = ".";
Return newIP;
}
Interface onIPInputDialogProcess {
Void onIPInputConfirm (String ip );
Void onIPInputCancel ();
}