Skip to content

Instantly share code, notes, and snippets.

@niusounds
Created March 12, 2014 11:50
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save niusounds/9505361 to your computer and use it in GitHub Desktop.
Save niusounds/9505361 to your computer and use it in GitHub Desktop.
Custom SeekBar for Android that treat its value as float type. floatMax and floatMin can be negative value.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FloatSeekBar">
<attr name="floatMax" format="float" />
<attr name="floatMin" format="float" />
</declare-styleable>
</resources>
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.SeekBar;
public class FloatSeekBar extends SeekBar {
private float max = 1.0f;
private float min = 0.0f;
public FloatSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyAttrs(attrs);
}
public FloatSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
applyAttrs(attrs);
}
public FloatSeekBar(Context context) {
super(context);
}
public float getValue() {
return (max - min) * ((float) getProgress() / (float) getMax()) + min;
}
public void setValue(float value) {
setProgress((int) ((value - min) / (max - min) * getMax()));
}
private void applyAttrs(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FloatSeekBar);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.FloatSeekBar_floatMax:
this.max = a.getFloat(attr, 1.0f);
break;
case R.styleable.FloatSeekBar_floatMin:
this.min = a.getFloat(attr, 0.0f);
break;
}
}
a.recycle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment