我有一個EditText,我希望用戶能夠輸入MAC地址。在Android上輸入正確格式的MAC地址
如何限制用戶只輸入A,B,C..F和數字並以正確的格式寫入(00:11:22:33:44:55)?
如何驗證?
編輯:我發現這個代碼,做我所需要的,但與IP地址。我試圖使用你建議的正則表達式,但它們不起作用。
public void showIP(){
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_PHONE);
input.setSingleLine();
InputFilter[] filters = new InputFilter[1];
//filter used to allow only IPv4 style address
filters[0] = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
if (!resultingTxt.matches("^[\\dA-F]{2}(?::[\\dA-F]{2}){5}$")) {
return "";
} /*else {
String[] splits = resultingTxt.split("\\:");
for (int i=0; i<splits.length; i++) {
if (Integer.valueOf(splits[i]) >) {
return "";
}
}
}*/
}
return null;
}
};
input.setFilters(filters);
input.setText(serverIP);
new AlertDialog.Builder(this)
.setTitle(R.string.ServerIP)
.setMessage("Change SERVER IP")
.setView(input)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
serverIP=input.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("IP", input.getText().toString());
// Commit the edits!
editor.commit();
view.updateServerIP();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
}).show();
}
只有4個字段或使一個單一dinamycally工作(廣告':'等)。 – shkschneider
我做了一個單一的工作dinameically – 88mdil
分隔符可以是連字符'-'或冒號':' – Anirudha