views:

119

answers:

1

Hello,

What I want to do is I am working on a game of life program. I want to take the time delay and make it a preference, but I want to make it available for people to type in a specific time. The number can be in miliseconds or seconds.

However I'm a little stuck on how to proceed, I haven't been able to find a simple preference that already handles this, but there might be one. Is there an easy way to make this preference and confirm that the entered data is an integer or afloat?

+1  A: 

If you are using a PreferenceActivity which you probably are, there is not one available.

You will need to do something like this:

    /**
 * Checks that a preference is a valid numerical value
 */
Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        //Check that the string is an integer.
        return numberCheck(newValue);
    }
};

private boolean numberCheck(Object newValue) {
    if( !newValue.toString().equals("")  &&  newValue.toString().matches("\\d*") ) {
        return true;
    }
    else {
        Toast.makeText(ActivityUserPreferences.this, newValue+" "+getResources().getString(R.string.is_an_invalid_number), Toast.LENGTH_SHORT).show();
        return false;
    }
}


    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //get XML preferences
    addPreferencesFromResource(R.xml.user_preferences);


    //get a handle on preferences that require validation
    delayPreference = getPreferenceScreen().findPreference("pref_delay");

    //Validate numbers only
    delayPreference.setOnPreferenceChangeListener(numberCheckListener);

}
jax
only issue is delayPreference isn't defined in the example (it's a Preference I know) Also this is code for inside the preference activity class, but seems to work well, thank you very much.
Kinglink