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(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]) > 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(); 
    } 

You May Also Like