Skip to content

Instantly share code, notes, and snippets.

@afarber
Last active August 29, 2015 14:21
Show Gist options
  • Save afarber/160addbc2d56b5a4d757 to your computer and use it in GitHub Desktop.
Save afarber/160addbc2d56b5a4d757 to your computer and use it in GitHub Desktop.
SeekBarPreference for Android: inline (not dialog-based) and saves slider progress as integer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical" >
<SeekBar
android:id="@+id/seekbar"
android:layout_width="0dp"
android:layout_weight="80"
android:layout_height="wrap_content" />
<TextView
android:id="@android:id/summary"
android:layout_width="0dp"
android:layout_weight="20"
android:layout_height="wrap_content" />
</LinearLayout>
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class SeekBarPreference extends Preference implements OnSeekBarChangeListener {
private SeekBar mSeekBar;
private int mProgress;
public SeekBarPreference(Context context) {
this(context, null, 0);
}
public SeekBarPreference(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setLayoutResource(R.layout.preference_seekbar);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mSeekBar = (SeekBar) view.findViewById(R.id.seekbar);
mSeekBar.setProgress(mProgress);
mSeekBar.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser)
return;
setValue(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// not used
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// not used
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedInt(mProgress) : (Integer) defaultValue);
}
public void setValue(int value) {
if (shouldPersist()) {
persistInt(value);
}
if (value != mProgress) {
mProgress = value;
notifyChanged();
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment