androidx.customview包主要有2个helper, ExploreByTouchHelper 和 ViewDragHelper。
通过ExploreByTouchHelper可以让自定义View被talkBack等无障碍服务识别和读取。
通过ViewDragHelper实现下拉刷新 和 上拉加载更多。
ExploreByTouchHelper
ExploreByTouchHelper 是一个工具类,为了更好的支持无障碍交互,提供信息给无障碍服务和管理无障碍焦点。
例如 :TalkBack会从View中取出相关的无障碍内容,然后提示给用户。 普通的控件,例如textView,EditText的xml 配置android:contentDescripton属性就会被talkBack读取出来。如果
如果需要屏蔽,可以在xml设置IMPORTANT_FOR_ACCESSIBILITY_NO来屏蔽内容被读取。
设置IMPORTANT_FOR_ACCESSIBILITY_YES 表示有无障碍焦点,可以被talkBack读取。
对于自定义的View,里面各种图形无障碍化,需要被talkBack识别。我们就需要借助
ExploreByTouchHelper来实现。
主要的API :
提供匹配view绝对坐标系x,y对应的虚拟item , 返回virtualViewid
int getVirtualViewAt(x,y)
把所有可见的item的virtualViewId填充到List集合中。
void getVisibleVirtualViews(List virtualViewIds)
给当前VirtualView填充信息。包括setScrollable,setEnabled,setContentDescription()
void onPopulateEventForVirtualView(int virtualViewId, AccessibilityEvent event)
当前VirtualView执行action,action包括Action_click, Action_Accessibility_Focus等
boolean onPerformActionForVirtualView(int virtualViewId,int action, Bundle arguments)
如何使用:
1 : 继承ExploreByTouchHelper,实现上述4个方法。
2 : 将事件传递给helper处理。
3 : 给View设置无障碍代理。
ViewDragHelper
ViewDragHelper is a utility class for writing custom ViewGroups.
It offers a number of useful operations and state tracking for allowing a user to drag and
reposition views within their parent ViewGroup.
ViewDraghelper 是一个创建自定义view的工具类,提供了大量有用的操作,捕获状态,并且允许用户拖拽View和设置在父viewGroup中的位置。
实现的CallBack的API:
STATE_IDLE : 静止状态。拖拽结束,动画停止,都是这个状态。
STATE_DRAGGING:正在被拖拽。Motion输入
STATE_SETTLIN :释放之后,View朝最终位置fling。
public void onViewDragStateChanged(int state) {}
view已经被捕获,拖拽和fling时候回调。
changView : 捕获的View;
left :等于oldleft + dx 要滚动最终位置的left
top : 等于oldtop + dy 要滚动到最终位置的top
dx :水平方向增量。
dy : 竖直方向增量。
onViewPositionChanged(@NonNull View changedView,int left,int top,int dx, int dy)
当View被捕获的时候回调。
public void onViewCaptured(@NonNull View capturedChild,int activePointerId) {}
当子View不在被拖拽。如果调用settleCapturedViewAt(int, int) or
flingCapturedView(int, int, int, int) 则view进入STATE_SETTLING状态,否则进入STATE_IDLE状态。
public void onViewReleased(@NonNull View releasedChild,float xvel,float yvel)
边界触摸的时候回调: EDGE_LEFT, EDGE_TOP, EDGE_RIGHT, EDGE_BOTTOM,通过触摸点x,y值确定边界。
drawerLayout : 这个方法设置捕获的View探出一段距离,方便拖拽。
public void onEdgeTouched(int edgeFlags,int pointerId) {}
设置拖拽的View的边界锁定。
public boolean onEdgeLock(int edgeFlags)
当View已经从某个边界被捕获时回调。
onEdgeDragStarted(int edgeFlags,int pointerId)
返回View的在布局中的index.
public int getOrderedChildIndex(int index)
返回水平方向滚动的范围。 0 表示水平方向不可滚动。
public int getViewHorizontalDragRange(@NonNull View child)
返回竖直方向滚动的范围。 0 表示竖直方向不可滚动。
public int getViewVerticalDragRange(@NonNull View child)
用户尝试捕获该View。返回true,表示该View被捕获。
public abstract boolean tryCaptureView(@NonNull View child,int pointerId);
水平方向:确定可以拖拽的left的可取值。
如果水平方向可以移动,但是上次的left和这次的left值相同,则水平方向表示不能拖拽了。viewDragHelper则返回false,不拦截这次事件。
通常为 parent.LeftPadding() <= left <= parent.Width() - view.width()
public int clampViewPositionHorizontal(@NonNull View child,int left,int dx)
竖直方向:确定可以拖拽top的可取值。
如果水平方向可以移动,但是上次的top和这次的top值相同,则竖直方向表示不能拖拽了。viewDragHelper则返回false,不拦截这次事件。
通常为 parent.topPadding() <= top <= parent.height() - view.Height()
clampViewPositionVertical(@NonNull View child,int top,int dy)
使用方式:
1 : 继承callBack , 实现上述部分方法。
2 : 和ViewGroup绑定。
ViewDragHelper.create(this,1.0f,new DragCallBack());
3 : 传递onInterceptTouchEvent(MotionEvent ev) 和 onTouchEven(MotionEvent ev)
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mDragHelper.shouldInterceptTouchEvent(ev);
}
拦截事件: 通过mCallback.clampViewPositionVertical() 和mCallback.clampViewPositionVertical()判断该事件是否需要拦截。达到拦截条件则回调mCallback.tryCaptureView() , 如果不必拦截,则该事件向下传递,。
@Override
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
处理captureView的down事件。回调mCallback.tryCaptureView()
处理captureView的Move事件。 回调mCallback.onViewPositionChanged()
dragTo(mCapturedView.getLeft() +idx,mCapturedView.getTop() +idy,idx,idy);
处理captureView的Up事件。 回调mCallback.onViewReleased()
示例: 利用ViewDragHelper实现下拉刷新和上拉加载更多。
整个代码:
protected void onFinishInflate() {
super.onFinishInflate();
Log.d(TAG, "onFinishInflate: ");
contentView = getChildAt(2);
headerVisiable = ((LinearLayout) headerView).getChildAt(1);
headerVisiableLoadView = (AVLoadingIndicatorView) (((RelativeLayout) headerVisiable).getChildAt(1));
headerVisiableLoadView.show();
}
public View getHeaderView(Context context) {
return LayoutInflater.from(context).inflate(defaultHeader, null);
}
public View getFootView(Context context) {
return LayoutInflater.from(context).inflate(defaultFooter, null);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d(TAG, "onMeasure: ");
for (int i = 0; i < getChildCount(); i++) {
measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "onMeasure: " + getChildAt(i).getMeasuredWidth() + " height " + getChildAt(i).getMeasuredHeight());
}
int width = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY);
int height = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.EXACTLY);
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "onLayout:" + skipLayout);
if (!skipLayout) {
headerView.layout(0, -headerView.getMeasuredHeight(), headerView.getMeasuredWidth(), 0);
footView.layout(0, getMeasuredHeight(), footView.getMeasuredWidth(), getMeasuredHeight() + footView.getMeasuredHeight());
contentView.layout(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight());
} else {
skipLayout = false;
Log.d(TAG, "onLayout: " + headerView.getTop() + " " + contentView.getTop());
footView.layout(0, footView.getTop(), footView.getMeasuredWidth(), getMeasuredHeight() + footView.getBottom());
headerView.layout(0, headerView.getTop(), headerView.getMeasuredWidth(), headerView.getBottom());
contentView.layout(0, contentView.getTop(), contentView.getMeasuredWidth(), contentView.getBottom());
}
}
float initY = 0f;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean interceptFlag = mDragHelper.shouldInterceptTouchEvent(ev);
boolean canScrollUp = contentView.canScrollVertically(-1);
boolean canScrollDown = contentView.canScrollVertically(1);
Log.d(TAG, "onInterceptTouchEvent: down " + canScrollDown + " up = " + canScrollUp);
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
initY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
float currY = ev.getY();
//footer的多点触摸时候,强制拦截事件给viewDraghelper处理
if (currY - initY < 0 && !canScrollDown && Math.abs(currY - initY) > mDragHelper.getTouchSlop() && !interceptFlag) {
Log.d(TAG, "onInterceptTouchEvent: --------- " + interceptFlag);
return true;
} /*else if (currY - initY > 0 && canScrollUp && Math.abs(currY - initY) > mDragHelper.getTouchSlop()) { //footer
Log.d(TAG, "onInterceptTouchEvent: ++++++++" + interceptFlag);
return interceptFlag;
} else if (canScrollUp && Math.abs(currY - initY) > mDragHelper.getTouchSlop()) {
return false;
}*/
break;
}
Log.d(TAG, "onInterceptTouchEvent: " + interceptFlag);
return interceptFlag;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
class DragCallBack extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
skipLayout = true;
headerVisiableLoadView.setVisibility(View.GONE);
headerVisiableLoadView.hide();
return child == contentView;
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return headerView.getMeasuredHeight();
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
boolean up = child.canScrollVertically(-1);
boolean down = child.canScrollVertically(1);
Log.d(TAG, "clampViewPositionVertical: " + up + " " + down + " " + dy + " " + top);
if (up == false && down == true) {
int finalTop = top;
if (dy > 0) {
finalTop = (int) (finalTop - dy * dampingRatio(top, headerView.getMeasuredHeight()));
// Log.d(TAG, "clampViewPositionVertical: " + finalTop + " " + top + " " + (dampingRatio(top)));
}
Log.d(TAG, "clampViewPositionVertical: 0 ");
return Math.min(headerView.getMeasuredHeight(), Math.max(0, finalTop));
} else if (up && !down) {
int finalTop = top;
if (dy < 0) {
// finalTop = (int) (finalTop + dy * dampingRatio(top,footView.getMeasuredHeight()));
// Log.d(TAG, "clampViewPositionVertical: " + finalTop + " " + top + " " + (dampingRatio(top)));
}
int max = Math.max(-footView.getMeasuredHeight(), Math.min(0, finalTop));
Log.d(TAG, "clampViewPositionVertical: 1 " + max + " " + top);
return max;
} else {
Log.d(TAG, "clampViewPositionVertical: 2 ");
return child.getTop();
}
}
public float dampingRatio(int top, int totalHeight) {
float diffRatio = top * 1.0f / totalHeight;
return diffRatio;
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
Log.d(TAG, "onViewCaptured: ");
super.onViewCaptured(capturedChild, activePointerId);
removeCallbacks(mHeaderRunnable);
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
super.onViewPositionChanged(changedView, left, top, dx, dy);
ViewCompat.offsetTopAndBottom(headerView, dy);
ViewCompat.offsetTopAndBottom(footView, dy);
Log.d(TAG, "onViewPositionChanged: " + changedView.getTop() + " " + changedView.getBottom());
Log.d(TAG, "onViewPositionChanged: " + top + " 1 " + dy);
if (top == headerVisiable.getMeasuredHeight() && dy < 0) {
Log.d(TAG, "onViewPositionChanged: " + top + " " + dy);
skipLayout = true;
headerVisiableLoadView.show();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
Log.d(TAG, "onViewReleased: " + yvel);
if (contentView.getTop() >= headerVisiable.getMeasuredHeight()) {
Log.d(TAG, "onViewReleased: " + headerVisiable.getMeasuredHeight());
mDragHelper.smoothSlideViewTo(releasedChild, 0, headerVisiable.getMeasuredHeight());
} else if (contentView.getTop() > 0 && contentView.getTop() < headerVisiable.getMeasuredHeight()) {
mDragHelper.smoothSlideViewTo(releasedChild, 0, 0);
} else if (contentView.getTop() < 0 && contentView.getTop() < -footView.getMeasuredHeight() / 2) {
mDragHelper.smoothSlideViewTo(releasedChild, 0, -footView.getMeasuredHeight());
} else if (contentView.getTop() > -footView.getMeasuredHeight() / 2) {
mDragHelper.smoothSlideViewTo(releasedChild, 0, 0);
}
invalidate();
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
super.onEdgeDragStarted(edgeFlags, pointerId);
}
@Override
public void onViewDragStateChanged(int state) {
Log.d(TAG, "onViewDragStateChanged: " + contentView.getTop() + "..." + headerVisiable.getMeasuredHeight());
if (state == ViewDragHelper.STATE_IDLE && contentView.getTop() == headerVisiable.getMeasuredHeight()) {
skipLayout = true;
headerVisiableLoadView.setVisibility(View.VISIBLE);
headerVisiableLoadView.show();
postDelayed(mHeaderRunnable, 2000);
} else if (state == ViewDragHelper.STATE_IDLE && contentView.getTop() == -footView.getMeasuredHeight()) {
postDelayed(mHeaderRunnable, 2000);
}
}
}
private final Runnable mHeaderRunnable = new Runnable() {
@Override
public void run() {
mDragHelper.smoothSlideViewTo(contentView, 0, 0);
invalidate();
}
};
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
Log.d(TAG, "computeScroll: " + true);
ViewCompat.postInvalidateOnAnimation(this);
}
}