我想知道是否有辦法檢查某人在共享首選項/設置屏幕上輸入的內容以進行驗證。用戶觸摸IP輸入選項,彈出一個edittext對話框,我試圖限制他們可以輸入的東西像一個標準的IP地址(即0-255.0-255.0-255.0-255)我已經看過很多在線論壇並看到與REGEX和模式不同的事情的例子,這是我迄今爲止,但絕對沒有發生....任何人都可以幫我嗎?我將不勝感激!檢查共享首選項設置屏幕上的editText
public class PrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener
{
private EditTextPreference ipTextBox;
private String whatWasTyped;
private String previousText = "";
private Editor myEditor;
final Pattern IP_ADDRESS = Pattern
.compile("^((1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)\\.){3}(?:1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)$");
private String IP_FROM_PREFS = "ipAddressPref";
SharedPreferences prefs;
@Override
/**
* The onCreate method handles thing when starting this activity,
* mainly display the activity_settings.xml.
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// pattern for IP address validation
addPreferencesFromResource(R.layout.activity_settings);
// prefs.registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Get a reference to the preferences
ipTextBox = (EditTextPreference) getPreferenceScreen().findPreference(
IP_FROM_PREFS);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key)
{
// check prefs value for IP.
if (key.equals(IP_FROM_PREFS))
{
whatWasTyped = prefs.getString(IP_FROM_PREFS, "");
CharSequence s = whatWasTyped;
if (IP_ADDRESS.matcher(s).matches())
{
previousText = s.toString();
myEditor = prefs.edit();
myEditor.putString(IP_FROM_PREFS, previousText);
myEditor.commit();
} else
{
//if the format does not match, put up an error message
// or something.
}
}
}
@Override
protected void onResume()
{
super.onResume();
// Setup the initial values
// mCheckBoxPreference.setSummary(sharedPreferences.getBoolean(key,
// false) ? "Disable this setting" : "Enable this setting");
// mListPreference.setSummary("Current value is " +
// sharedPreferences.getValue(key, ""));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
previousText = prefs.getString(IP_FROM_PREFS, "");
}
@Override
protected void onPause()
{
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
,因爲這是共享首選項屏幕上創建的東西,有沒有按鈕的ID,等...
在這一行中:addPreferencesFromResource(R.layout.activity_settings);你應該把activity_settings.xml放到XML文件夾中,而不是佈局文件夾 – 2012-08-03 20:09:37
抱歉,我糾正了我的模式:\ b(?:(?: 25 [0-5] | 2 [0-4] \ d | 1 \ d {2} |?\ d \ d)\){3}(?: 25 [0-5] | 2 [0-4] \ d | 1 \ d {2} |?\ d \ d)\ b – godspeedlee 2012-08-03 20:13:22