consp1racy / android-support-preference

Android Preferences according to Material design specs
Apache License 2.0
331 stars 49 forks source link

How to set step size or increment of a SeekBarPreference? #72

Closed kaustav07 closed 7 years ago

kaustav07 commented 7 years ago

I tried to set it by setting in xml like android:progress="desired value" Also tried to set it from java code like -

final SeekBarPreference wait1 = (SeekBarPreference) findPreference("Wait1"); wait1.setSeekBarIncrement(2);

but so far no luck, can you help on this?

consp1racy commented 7 years ago

Example: You want a seekbar from 3 to 9, step size 2. Setup a seekbar with min = 3 and max = 6. Then attach a change listener and your output = min + (max - min) * 2.

kaustav07 commented 7 years ago

can you please give me some code example?it will really help...Thank You for sharing

consp1racy commented 7 years ago

Consider this seek bar preference:

<SeekBarPreference
    android:defaultValue="50"
    android:key="someKey"
    android:max="100"
    app:asp_min="0"/>

This seek bar will allow storing whole numbers <0;100>, default 50, step size 1.

If you want seekbar to increment by two at a time, you'll have to half the range and multiply stored value by two when used:

<SeekBarPreference
    android:defaultValue="25"
    android:key="someKey"
    android:max="50"
    app:asp_min="0"/>

final SeekBarPreference sbp = (SeekBarPreference) findPreference("someKey"); 
sbp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        final int progress = (int) value;
        final int actualValue = progress * 2;
        // Display the value or do whatever you need with it.
    }
})

Remember, everytime you get the value from the preference, you have to multiply it by step size. Make a helper method for it, so you can't make a mistake.