I have extended the HorizontalScrollView
class to implement a certain behavior. Under the LinearLayout inside my CustomHorizontalScrollView
I have only 2 child views (lets say ImageView
). When the user scrolls more than 50% to one direction, i want my CustomHorizontalScrollView
to auto-scroll to the end of the same direction. This is how I implemented it:
CustomHorizontalScrollView
class:
public class CustomHorizontalScrollView extends HorizontalScrollView {
private static float downCoordinates = -1;
private static float upCoordinates = -1;
private static int currentPosition = 0;
public CustomHorizontalScrollView(Context ctx) {
super(ctx);
}
public CustomHorizontalScrollView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN && downCoordinates == -1) {
downCoordinates = ev.getX();
}
else if (ev.getAction() == MotionEvent.ACTION_UP && upCoordinates == -1) {
upCoordinates = ev.getX();
int scrollViewWidth = this.getMeasuredWidth();
double dist = downCoordinates - upCoordinates;
if (Math.abs(dist) > scrollViewWidth / 2) {
//this.setSmoothScrollingEnabled(true);
// Going forwards
if (dist > 0) {
int max = ((LinearLayout)this.getChildAt(0)).getChildAt(1).getMeasuredWidth();
currentPosition = max;
this.scrollTo(max, 0);
}
// Going backwards
else {
currentPosition = 0;
this.scrollTo(0, 0);
}
}
// reseting the saved Coordinates
downCoordinates = -1;
upCoordinates = -1;
}
return super.onTouchEvent(ev);
}
}
Up until here - everything works. The thing is that I want the auto-scrolling to be done smoothly so i tried using the smoothScrollTo
function instead of the scrollTo
function but then, nothing happens (as in no auto-scrolling). i tried declaring this:
this.setSmoothScrollingEnabled(true);
but also with no success.
Have you tried this?
this.post(new Runnable() {
public void run() {
this.smoothScrollTo(0, this.getBottom());
}
});