我想知道是否有办法检查某人在共享首选项/设置屏幕上输入的内容以进行验证。用户触摸输入输入选项,弹出一个编辑文本对话框,我试图限制他们可以输入的东西,如标准IP地址(即0-255.0-255.0-255.0-255)我已经在众多的在线论坛中查找并看到了REGEX和模式的不同事物的例子,这是我到目前为止所做的,但绝对没有发生任何事情......任何人都可以帮助我吗?我将不胜感激!
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等...
答案 0 :(得分:0)
刚写
whatWasTyped.replace(s, previousText);
不会将之前的文本分配给共享首选项,您需要将其分配回共享首选项并提交。