SoFunction
Updated on 2025-03-08

ScrollView nested ScrollView solution in android


package ;
import ;
import ;
import ;
import ;
import ;
public class InnerScrollView extends ScrollView {
/**
*/
public ScrollView parentScrollView;
public InnerScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private int lastScrollDelta = 0;
public void resume() {
overScrollBy(0, -lastScrollDelta, 0, getScrollY(), 0, getScrollRange(), 0, 0, true);
lastScrollDelta = 0;
}
int mTop = 10;
/**
* Roll targetView to the top
*/
public void scrollTo(View targetView) {
int oldScrollY = getScrollY();
int top = () - mTop;
int delatY = top - oldScrollY;
lastScrollDelta = delatY;
overScrollBy(0, delatY, 0, getScrollY(), 0, getScrollRange(), 0, 0, true);
}
private int getScrollRange() {
int scrollRange = 0;
if (getChildCount() > 0) {
View child = getChildAt(0);
scrollRange = (0, () - (getHeight()));
}
return scrollRange;
}
int currentY;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (parentScrollView == null) {
return (ev);
} else {
if (() == MotionEvent.ACTION_DOWN) {
// Intercept the scroll event of the parent scrollview
currentY = (int)();
setParentScrollAble(false);
return (ev);
} else if (() == MotionEvent.ACTION_UP) {
// Restore the scroll event to the parent Scrollview
setParentScrollAble(true);
} else if (() == MotionEvent.ACTION_MOVE) {
}
}
return (ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
View child = getChildAt(0);
if (parentScrollView != null) {
if (() == MotionEvent.ACTION_MOVE) {
int height = ();
height = height - getMeasuredHeight();
// ("height=" + height);
int scrollY = getScrollY();
// ("scrollY" + scrollY);
int y = (int)();
// Slide downward
if (currentY < y) {
if (scrollY <= 0) {
// If you slide down to the head, hand the scroll to the parent Scrollview
setParentScrollAble(true);
return false;
} else {
setParentScrollAble(false);
}
} else if (currentY > y) {
if (scrollY >= height) {
// If you slide up to the head, hand the scroll to the parent Scrollview
setParentScrollAble(true);
return false;
} else {
setParentScrollAble(false);
}
}
currentY = y;
}
}
return (ev);
}
/**
* Whether to hand over the scrolling event to the parent scrollview
*
* @param flag
*/
private void setParentScrollAble(boolean flag) {
(!flag);
}
}