I have a seek bar inside a scroll view.When some one accidentally touches the slider during scrolling slider changes. I want to change the slider value only when the i drag the thumb. Can anyone help me with this?
1 Answers
I'm not aware of any builtin option that allow you to do what you're looking for, but you can easily extend the default SeekBar implementation and override the handling of touch events. A basic implementation will look somewhat like this:
public class ThumbOnlySeekBar extends SeekBar {
private Drawable mThumb;
public ThumbOnlySeekBar(Context context) {
super(context);
}
public ThumbOnlySeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ThumbOnlySeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override public void setThumb(Drawable thumb) {
super.setThumb(thumb);
mThumb = thumb;
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (!mThumb.getBounds().contains((int)event.getX(), (int)event.getY())) return true;
return super.onTouchEvent(event);
}
}
As SeekBar does not have a getThumb()
method that returns the drawable used for the thumb, it's necessary to override setTumb(...)
to keep track of the thumb set. You can look up the source for SeekBar and see that it always nicely calls this method to set the thumb drawable - convenient for us. :)
The handling of touch events is basically very simple: just do a test whether the touch coordinates are inside the bounding box of the thumb drawable. Obviously, if you have circular thumb, you could apply a slightly different test, but the idea should be clear. If the touch event was not on the thumb, simply return it being handled and don't propagate it.

- 45,303
- 10
- 103
- 116