Discover the current position of the childs inside a ScrollView
I has a subclass of ScrollView that paginate its childs, it's something like this.
It's not the only thing that this class does, it's also give it's TouchsEvents if any child was able to handle it (returns true onTouchEvent) But my problem is, on the method centralizeContent(), all the RectF has the actual value with the scroll of the component. In the method dispatch, all the values are the same.
public class ScrollViewVertical extends ScrollView {
private boolean paging;
public ScrollViewVertical(Context context) {
super(context);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(dispatch((ViewGroup)getChildAt(0), ev))
return true;
return onTouchEvent(ev);
}
public boolean dispatch(ViewGroup view, MotionEvent ev) {
for (int i = 0; i < view.getChildCount();i++) {
View v = view.getChildAt(i);
RectF viewBounds = new RectF(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
System.out.println(viewBounds);
if (viewBounds.contains(ev.getX(), ev.getY()))
return v.dispatchTouchEvent(ev);
}
return false;
}
public boolean onTouchEvent(MotionEvent evt) {
if (evt.getAction() == MotionEvent.ACTION_UP)
if (isPaging())
centralizeContent();
return super.onTouchEvent(evt);
}
private void centralizeContent() {
int currentY = getScrollY() + getHeight() / 2;
ViewGroup content = (ViewGroup) getChildAt(0);
for (int i = 0; i < content.getChildCount(); i++) {
View child = content.getChildAt(i);
System.out.println(BoundsUtils.from(child));
if (child.getTop() < currentY && child.getBottom() > currentY) {
smoothScrollTo(0, child.getTop());
break;
}
}
}
}
Note that I'm getting the child(0) on both cases.
Just to clarify, suppose I have 3 ImageViews that is 1000 width and 500 height
on centralizeContent(), I'll have these values (let's say we scrolled 90):
RectF(0.0, 0.0, 1000.0, 500.0)
RectF(0.0, 90.0, 1000.0, 500.0)
RectF(0.0, 180.0, 1000.0, 500.0)
But in the dispatch method, it's come like this (with any scroll amount):
RectF(0.0, 0.0, 1000.0, 500.0)
RectF(0.0, 0.0, 1000.0, 500.0)
RectF(0.0, 0.开发者_StackOverflow社区0, 1000.0, 500.0)
I cannot handle the events properly without knowing the exactly position of the childs.
精彩评论