canScrollVertically 的用法
https://developer.android.com/reference/android/widget/ScrollView
canScrollVertically(-1)返回true的时候表示滑动在滑动到顶部
public boolean canScrollVertically (int direction)
Check if this view can be scrolled vertically in a certain direction.
Parameters
direction int: Negative to check scrolling up, positive to check scrolling down.
Returns
boolean true if this view can be scrolled in the specified direction, false otherwise.
源码 源码连接
/**
* Check if this view can be scrolled vertically in a certain direction.
*
* @param direction Negative to check scrolling up, positive to check scrolling down.
* 小于零是向上滑动,大于零是乡下滑动
* @return true if this view can be scrolled in the specified direction, false otherwise.
*/
public boolean canScrollVertically(int direction) {
final int offset = computeVerticalScrollOffset();
final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
判断是否滑动到底部,顶部
/**
* 判断是否滑动到底部
* @param direction
* @return
*/
private boolean canScrollVerticallyBottomOrTop(int direction) {
// 判断 scrollView 当前滚动位置在顶部
if(direction<0){
if (getScrollY() == 0) {
return true;
} else {
return false;
}
}
// 判断scrollview 滑动到底部
// scrollY 的值和子view的高度一样,这人物滑动到了底部
if(direction>0){
if (getChildAt(0).getHeight() - getHeight()
== getScrollY()) {
return true;
} else {
return false;
}
}
return false;
}
处理Scroll View 与竖向滑的ViewPager的滑动冲突
在自定义的Scroll View 中重写 dispatchTouchEvent当Scroll View 滑动到底部的时候把滑动事件交由父控件处理
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
if (canScrollVerticallyBottomOrTop(1)) {
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
}
return super.dispatchTouchEvent(ev);
}
SwipeRefreshLayout 与 NestedScrollView嵌套使用
处理多层嵌套 SwipeRefreshLayout >> LinearLayout >> NestedScrollView
的ScrollView滑动不流畅的问题
解决方案:在SwipeRefreshLayout 重写canChildScrollUp方法 如下:
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
@Override
public boolean canChildScrollUp() {
if (scrollView != null)
return scrollView.canScrollVertically(-1);
return super.canChildScrollUp();
}