判断view能否上滑

判断View能否上滑


最近在看下拉刷新控件的源码,看到一段判断控件是否可以上滑的代码,摘抄下来,与小伙伴们共享

1. Ultra-Pull-To-Refresh判断

public static boolean canChildScrollUp(View view) {
    if (android.os.Build.VERSION.SDK_INT < 14) {
        if (view instanceof AbsListView) {
            final AbsListView absListView = (AbsListView) view;
            return absListView.getChildCount() > 0
                    && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                    .getTop() < absListView.getPaddingTop());
        } else {
            return view.getScrollY() > 0;
        }
    } else {
        return view.canScrollVertically(-1);
    }
}

2. SwipRefreshLayout判断

/**
 * @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.
 */
public boolean canChildScrollUp() {
    if (android.os.Build.VERSION.SDK_INT < 14) {
        if (mTarget instanceof AbsListView) {
            final AbsListView absListView = (AbsListView) mTarget;
            return absListView.getChildCount() > 0
                    && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                            .getTop() < absListView.getPaddingTop());
        } else {
            return ViewCompat.canScrollVertically(mTarget, -1) || mTarget.getScrollY() > 0;
        }
    } else {
        return ViewCompat.canScrollVertically(mTarget, -1);
    }
}

可以看出其实二者的判断差不多

  1. 在APi14之后,官方提供了canScrollVertically(int direction)方法,所以API14之后判断非常方便,官方文档的解释如下:

    翻译下来就是:当direction>0时,判断是否可以下滑,当direction<0时,判断是否可以上滑
  2. 但是在<API14时,只能自己动手了,不过好在这个判断也不复杂,
  3. 上图来说明一下view.getScrolly();
总结:就不总结了,因为没啥好说的

你可能感兴趣的:(widget)