編輯:關於Android編程
本文提供一種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();
}
學習知識:界面組成、事件監聽器====界面組成====1.用戶界面的基本組件叫做View,都是繼承android.view.View類,Android裡面預定義很多基本的
如圖:Menu: MainActivity.javapackage com.imooc.baidumap;import java.util.List;im
Android WebView常見問題解決方案匯總:就目前而言,如何應對版本的頻繁更新呢,又如何靈活多變地展示我們的界面呢,這又涉及到了web app與native ap
需求我們知道,Android系統本身有自帶的日歷控件,網絡上也有很多開源的日歷控件資源,但是這些日歷控件往往樣式較單一,API較多,不易於在實際項目中擴展並實現出符合具體