Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.