我有一个 EditText,我希望用户能够输入 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();
}