Android View刷新机制实例分析

2019-12-10 19:02:13于丽

2)ViewGrop的invalidateChild方法

public final void invalidateChild(View child, final Rect dirty) {
  ViewParent parent = this;
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {
    final int[] location = attachInfo.mInvalidateChildLocation;
    // 需要刷新的子View的位置 
    location[CHILD_LEFT_INDEX] = child.mLeft;
    location[CHILD_TOP_INDEX] = child.mTop;
    // If the child is drawing an animation, we want to copy this flag onto
    // ourselves and the parent to make sure the invalidate request goes through
    final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
    // Check whether the child that requests the invalidate is fully opaque
    final boolean isOpaque = child.isOpaque() && !drawAnimation && child.getAnimation() != null;
    // Mark the child as dirty, using the appropriate flag
    // Make sure we do not set both flags at the same time
    final int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
    do {
      View view = null;
      if (parent instanceof View) {
        view = (View) parent;
      }
      if (drawAnimation) {
        if (view != null) {
            view.mPrivateFlags |= DRAW_ANIMATION;
        } else if (parent instanceof ViewRoot) {
            ((ViewRoot) parent).mIsAnimating = true;
        }
      }
        // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
        // flag coming from the child that initiated the invalidate
      if (view != null && (view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
        view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
      }
      parent = parent.invalidateChildInParent(location, dirty);
    } while (parent != null);
  }
}
public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
  if ((mPrivateFlags & DRAWN) == DRAWN) {
    if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
            FLAG_OPTIMIZE_INVALIDATE) {
      // 根据父View的位置,偏移刷新区域 
      dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX, location[CHILD_TOP_INDEX] - mScrollY);
      final int left = mLeft;
      final int top = mTop;
      //计算实际可刷新区域 
      if (dirty.intersect(0, 0, mRight - left, mBottom - top) ||
            (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
        mPrivateFlags &= ~DRAWING_CACHE_VALID;
        location[CHILD_LEFT_INDEX] = left;
        location[CHILD_TOP_INDEX] = top;
        return mParent;
      }
    } else {
      mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
      location[CHILD_LEFT_INDEX] = mLeft;
      location[CHILD_TOP_INDEX] = mTop;
      dirty.set(0, 0, mRight - location[CHILD_LEFT_INDEX],
            mBottom - location[CHILD_TOP_INDEX]);
        return mParent;
      }
    }
    return null;
}