Getting value from custom SeekBarPreference

2019-07-24 19:36发布

问题:

I found this code on internet and thought I would give it a try. I put it in my preferences and it was exaclt the way I wanted it to be but my only problem is that I cant get the value of SeekBar.

Here is the link to code that I am using in my preference:

http://android.hlidskialf.com/blog/code/android-seekbar-preference

and here is the part of preference xml:

<com.mypack.SeekBarPreference android:key="zoom"
        android:title="Zoom"
        android:summary=""
        android:dialogMessage="Zoom level"
        android:defaultValue="50"
        android:text=" %"
        android:max="100"
        />

can anyone tell me how to get value of seekbar after user has changed it in preferences window?

回答1:

You could use setOnPreferenceChangeListener():

SeekBarPreference mSeekBarPreference = new SeekBarPreference(this, null);
mSeekBarPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // TODO Auto-generated method stub
        int value = mSeekBarPreference.getProgress();
        // Or you just cast the newValue Object
        return true;
    }
});


回答2:

Should be just like any other preference.

implement SharedPreferences.OnSharedPreferenceChangeListener in your activity, then:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( YourActivity.this );
prefs.registerOnSharedPreferenceChangeListener( this );

-

public void onSharedPreferenceChanged( SharedPreferences prefs, String key ) {
    mZoomValue = prefs.getInt( "zoom", 50 );
}