Java Code Examples for android.graphics.Rect#intersects()

The following examples show how to use android.graphics.Rect#intersects() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WindowEventInterpreter.java    From talkback with Apache License 2.0 6 votes vote down vote up
private static boolean hasOverlap(
    AccessibilityWindowInfo windowA, AccessibilityWindowInfo windowB) {

  Rect rectA = AccessibilityWindowInfoUtils.getBounds(windowA);
  log("hasOverlap() windowA=%s rectA=%s", windowA, rectA);
  if (rectA == null) {
    return false;
  }

  Rect rectB = AccessibilityWindowInfoUtils.getBounds(windowB);
  log("hasOverlap() windowB=%s rectB=%s", windowB, rectB);
  if (rectB == null) {
    return false;
  }

  return Rect.intersects(rectA, rectB);
}
 
Example 2
Source File: CellLayout.java    From TurboLauncher with Apache License 2.0 6 votes vote down vote up
private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
        View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
    if (boundingRect != null) {
        boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
    }
    intersectingViews.clear();
    Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
    Rect r1 = new Rect();
    final int count = mShortcutsAndWidgets.getChildCount();
    for (int i = 0; i < count; i++) {
        View child = mShortcutsAndWidgets.getChildAt(i);
        if (child == dragView) continue;
        LayoutParams lp = (LayoutParams) child.getLayoutParams();
        r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
        if (Rect.intersects(r0, r1)) {
            mIntersectingViews.add(child);
            if (boundingRect != null) {
                boundingRect.union(r1);
            }
        }
    }
}
 
Example 3
Source File: ArtbookLayout.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
@Override
public HashMap<Object, FreeFlowItem> getItemProxies(
		int viewPortLeft, int viewPortTop) {

	Rect viewport = new Rect(viewPortLeft, 
							viewPortTop, 
							viewPortLeft + width, 
							viewPortTop + height);
	
	//Log.d(TAG, "Viewport: "+viewPortLeft+", "+viewPortTop+", "+viewport.width()+","+viewport.height());
	HashMap<Object, FreeFlowItem> ret = new HashMap<Object, FreeFlowItem>();

	Iterator<Entry<Object, FreeFlowItem>> it = map.entrySet().iterator();
	while (it.hasNext()) {
		Entry<Object, FreeFlowItem> pairs = it.next();
		FreeFlowItem p = (FreeFlowItem) pairs.getValue();
		if ( Rect.intersects(p.frame, viewport) ) {
			ret.put(pairs.getKey(), p);
		}
	}
	return ret;
	
}
 
Example 4
Source File: GalleryHeader.java    From EhViewer with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.P)
private boolean offsetVertically(Rect rect, View view, int width) {
  int offset = 0;

  measureChild(rect, view, width, 0, 0);
  rect.offset(lastX, lastY);

  for (Rect notch : displayCutout.getBoundingRects()) {
    if (Rect.intersects(notch, rect)) {
      offset = Math.max(offset, notch.bottom - lastY);
    }
  }

  if (offset != 0) {
    rect.offset(-lastX, -lastY);
    rect.offset(0, offset);
    return true;
  } else {
    return false;
  }
}
 
Example 5
Source File: PagerGridLayoutManager.java    From pager-layoutmanager with Apache License 2.0 6 votes vote down vote up
/**
 * 添加或者移除条目
 *
 * @param recycler    RecyclerView
 * @param displayRect 显示区域
 * @param i           条目下标
 */
private void addOrRemove(RecyclerView.Recycler recycler, Rect displayRect, int i) {
    View child = recycler.getViewForPosition(i);
    Rect rect = getItemFrameByPosition(i);
    if (!Rect.intersects(displayRect, rect)) {
        removeAndRecycleView(child, recycler);   // 回收入暂存区
    } else {
        addView(child);
        measureChildWithMargins(child, mWidthUsed, mHeightUsed);
        RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
        layoutDecorated(child,
                rect.left - mOffsetX + lp.leftMargin + getPaddingLeft(),
                rect.top - mOffsetY + lp.topMargin + getPaddingTop(),
                rect.right - mOffsetX - lp.rightMargin + getPaddingLeft(),
                rect.bottom - mOffsetY - lp.bottomMargin + getPaddingTop());
    }
}
 
Example 6
Source File: ViewUtils.java    From MultiView with Apache License 2.0 5 votes vote down vote up
public static View getFirstIntersectsChild(RecyclerView recyclerView) {
    int childCount = recyclerView.getChildCount();
    if (childCount > 0) {
        for (int i = 0; i < childCount; i++) {
            View child = recyclerView.getChildAt(i);
            Rect rect1=new Rect(recyclerView.getLeft(),recyclerView.getTop(), recyclerView.getRight(), recyclerView.getBottom());
            Rect rect2=new Rect(child.getLeft(),child.getTop(), child.getRight(), child.getBottom());
            if (Rect.intersects(rect1, rect2)) {
                return child;
            }
        }
    }
    return null;
}
 
Example 7
Source File: StrokeView.java    From sinovoice-pathfinder with MIT License 5 votes vote down vote up
/**
	 * Render the text
	 * 
	 * @see android.view.View#onDraw(android.graphics.Canvas)
	 */
    @Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		// ���Ʊ߿�
		drawBorder(canvas);

//		Rect r = canvas.getClipBounds();
		canvas.getClipBounds(mRectInDrawMethod);

		if (StrokeMgr.instance().isBrush) {
			canvas.drawBitmap(mPenScriptBitmap, 0, 0, mBrushPaint);
		} else {
			for (int i = 0; i < mPathInfo.size(); i++) {
				PathInfo pathInfo = mPathInfo.get(i);

				if (Rect.intersects(mRectInDrawMethod, pathInfo.rect)){
					mPaint.setColor(pathInfo.color);
				}
				
				canvas.drawPath(pathInfo.path, mPaint);
			}
			mPaint.setColor(mScriptColor);
			canvas.drawPath(mPath, mPaint);
		}
	}
 
Example 8
Source File: GalleryHeader.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.P)
private int getOffsetLeft(Rect rect, View view, int width) {
  int offset = 0;

  measureChild(rect, view, width, 0, 0);
  rect.offset(lastX, lastY);

  for (Rect notch : displayCutout.getBoundingRects()) {
    if (Rect.intersects(notch, rect)) {
      offset = Math.max(offset, notch.right - lastX);
    }
  }

  return offset;
}
 
Example 9
Source File: PreloadIconDrawable.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void draw(Canvas canvas) {
    final Rect r = new Rect(getBounds());
    if (canvas.getClipBounds(sTempRect) && !Rect.intersects(sTempRect, r)) {
        // The draw region has been clipped.
        return;
    }
    if (mIndicatorRectDirty) {
        initIndicatorRect();
    }
    final float iconScale;

    if ((mAnimationProgress >= ANIMATION_PROGRESS_STARTED)
            && (mAnimationProgress < ANIMATION_PROGRESS_COMPLETED)) {
        mPaint.setAlpha((int) ((1 - mAnimationProgress) * 255));
        mBgDrawable.setAlpha(mPaint.getAlpha());
        mBgDrawable.draw(canvas);
        canvas.drawOval(mIndicatorRect, mPaint);

        iconScale = ICON_SCALE_FACTOR + (1 - ICON_SCALE_FACTOR) * mAnimationProgress;
    } else if (mAnimationProgress == ANIMATION_PROGRESS_STOPPED) {
        mPaint.setAlpha(255);
        iconScale = ICON_SCALE_FACTOR;
        mBgDrawable.setAlpha(255);
        mBgDrawable.draw(canvas);

        if (mProgress >= 100) {
            canvas.drawOval(mIndicatorRect, mPaint);
        } else if (mProgress > 0) {
            canvas.drawArc(mIndicatorRect, -90, mProgress * 3.6f, false, mPaint);
        }
    } else {
        iconScale = 1;
    }

    canvas.save();
    canvas.scale(iconScale, iconScale, r.exactCenterX(), r.exactCenterY());
    mIcon.draw(canvas);
    canvas.restore();
}
 
Example 10
Source File: ItemizedOverlay.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
/**
 * Draws an item located at the provided screen coordinates to the canvas.
 *
 * @param canvas
 *            what the item is drawn upon
 * @param item
 *            the item to be drawn
 * @param curScreenCoords
 * @param pProjection
 * @return true if the item was actually drawn
 */
protected boolean onDrawItem(final Canvas canvas, final Item item, final Point curScreenCoords,
		final Projection pProjection) {

	

	final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK
			: 0);
	final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item
			.getMarker(state);
	final HotspotPlace hotspot = item.getMarkerHotspot();

	boundToHotspot(marker, hotspot);

	int x = mCurScreenCoords.x;
	int y = mCurScreenCoords.y;

	marker.copyBounds(mRect);
	mMarkerRect.set(mRect);
	mRect.offset(x, y);
	RectL.getBounds(mRect, x, y, pProjection.getOrientation(), mOrientedMarkerRect);
	final boolean displayed = Rect.intersects(mOrientedMarkerRect, canvas.getClipBounds());
	if (displayed) {
		if (pProjection.getOrientation() != 0) { // optimization: step 1/2
			canvas.save();
			canvas.rotate(-pProjection.getOrientation(), x, y);
		}
		marker.setBounds(mRect);
		marker.draw(canvas);
		if (pProjection.getOrientation() != 0) { // optimization: step 2/2
			canvas.restore();
		}
		marker.setBounds(mMarkerRect);
	}

	return displayed;
}
 
Example 11
Source File: WheelPickerLayoutManager.java    From RecyclerWheelPicker with Apache License 2.0 5 votes vote down vote up
private void fillView(RecyclerView.Recycler recycler, RecyclerView.State state) {

        if (getItemCount() <= 0 || state.isPreLayout()) return;

        // the visible area for the RecyclerView
        Rect displayArea = new Rect(0, mVerticalOffset, getHorizontalSpace(),
                getVerticalSpace() + mVerticalOffset);

        // remove invisible child
        Rect rect = new Rect();
        for (int i = 0; i < getChildCount(); i++) {
            View item = getChildAt(i);
            rect.set(getDecoratedLeft(item), getDecoratedTop(item),
                    getDecoratedRight(item), getDecoratedBottom(item));
            if (!Rect.intersects(displayArea, rect)) {
                removeAndRecycleView(item, recycler);
            }
        }

        // add visible child
        for (int i = 0; i < getItemCount(); i++) {
            Rect area = mItemAreas.get(i);
            if (Rect.intersects(displayArea, area)) {
                View child = recycler.getViewForPosition(i);
                addView(child);
                measureChildWithMargins(child, 0, 0);
                Rect childRect = new Rect();
                calculateItemDecorationsForChild(child, childRect);
                layoutDecorated(child, area.left, area.top - mVerticalOffset,
                        area.right, area.bottom - mVerticalOffset);
            }
        }
    }
 
Example 12
Source File: Lanes.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
private boolean intersects(int start, int count, Rect r) {
    for (int l = start; l < start + count; l++) {
        if (Rect.intersects(mLanes[l], r)) {
            return true;
        }
    }

    return false;
}
 
Example 13
Source File: ReactViewGroup.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void updateSubviewClipStatus(Rect clippingRect, int idx, int childIndexOffset) {
  View child = Assertions.assertNotNull(mAllChildren)[idx];
  sHelperRect.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
  boolean intersects = clippingRect
      .intersects(sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom);
  boolean needUpdateClippingRecursive = false;
  // We never want to clip children that are being animated, as this can easily break layout :
  // when layout animation changes size and/or position of views contained inside a listview that
  // clips offscreen children, we need to ensure that, when view exits the viewport, final size
  // and position is set prior to removing the view from its listview parent.
  // Otherwise, when view gets re-attached again, i.e when it re-enters the viewport after scroll,
  // it won't be size and located properly.
  Animation animation = child.getAnimation();
  boolean isAnimating = animation != null && !animation.hasEnded();
  if (!intersects && child.getParent() != null && !isAnimating) {
    // We can try saving on invalidate call here as the view that we remove is out of visible area
    // therefore invalidation is not necessary.
    super.removeViewsInLayout(idx - childIndexOffset, 1);
    needUpdateClippingRecursive = true;
  } else if (intersects && child.getParent() == null) {
    super.addViewInLayout(child, idx - childIndexOffset, sDefaultLayoutParam, true);
    invalidate();
    needUpdateClippingRecursive = true;
  } else if (intersects) {
    // If there is any intersection we need to inform the child to update its clipping rect
    needUpdateClippingRecursive = true;
  }
  if (needUpdateClippingRecursive) {
    if (child instanceof ReactClippingViewGroup) {
      // we don't use {@link sHelperRect} until the end of this loop, therefore it's safe
      // to call this method that may write to the same {@link sHelperRect} object.
      ReactClippingViewGroup clippingChild = (ReactClippingViewGroup) child;
      if (clippingChild.getRemoveClippedSubviews()) {
        clippingChild.updateClippingRect();
      }
    }
  }
}
 
Example 14
Source File: GridLayoutManager.java    From TvRecyclerView with Apache License 2.0 4 votes vote down vote up
private void fillEnd(RecyclerView.Recycler recycler) {
    int beginPos = findLastViewLayoutPosition() + 1;
    if (DEBUG) {
        Log.d(TAG, "fillEnd: beginPos=" + beginPos);
    }
    int itemCount = getItemCount();
    Rect displayRect = getDisplayRect();
    int rectCount;
    // Re-display the subview that needs to appear on the screen
    for (int i = beginPos; i < itemCount; i++) {
        rectCount = mItemsRect.size();
        Rect frame = mItemsRect.get(i);
        if (frame != null && i < rectCount) {
            if (Rect.intersects(displayRect, frame)) {
                View scrap = recycler.getViewForPosition(i);
                if (mAdapter.getColumns() > 0) {
                    measureChild(scrap, getItemWidth(i), getItemHeight(i));
                } else {
                    measureChild(scrap);
                }
                addView(scrap);
                if (mOrientation == HORIZONTAL) {
                    layoutDecoratedWithMargins(scrap,
                            frame.left - mHorizontalOffset,
                            frame.top,
                            frame.right - mHorizontalOffset,
                            frame.bottom);
                } else {
                    layoutDecoratedWithMargins(scrap,
                            frame.left,
                            frame.top - mVerticalOffset,
                            frame.right,
                            frame.bottom - mVerticalOffset);
                }
                if (DEBUG) {
                    Log.d(TAG, "fillEnd: scroll down/right recycle=i=" + i
                            + "=rectCount=" + rectCount);
                }
            }
        } else if (rectCount < itemCount) {
            View child = recycler.getViewForPosition(i);
            Rect itemRect = calculateViewSizeByPosition(child, i);
            if (!Rect.intersects(displayRect, itemRect)) {
                recycler.recycleView(child);
                return;
            }
            addView(child);
            if (mOrientation == HORIZONTAL) {
                layoutDecoratedWithMargins(child,
                        itemRect.left - mHorizontalOffset,
                        itemRect.top,
                        itemRect.right - mHorizontalOffset,
                        itemRect.bottom);
                mTotalSize = itemRect.right;
            } else {
                layoutDecoratedWithMargins(child,
                        itemRect.left,
                        itemRect.top - mVerticalOffset,
                        itemRect.right,
                        itemRect.bottom - mVerticalOffset);
                mTotalSize = itemRect.bottom;
            }

            mItemsRect.put(i, itemRect);
            if (DEBUG) {
                Log.d(TAG, "fillEnd: scroll down/right new item=i=" + i
                        + "=rectCount=" + rectCount);
            }
        }
    }
}
 
Example 15
Source File: RectUtils.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Find the largest sub-rectangle that doesn't intersect a specified one. <strong>Note:</strong>
 * {@code rectToModify} and {@code otherRect} will be sorted after operation.
 *
 * @param rectToModify The rect that may be modified to avoid intersections
 * @param otherRect The rect that should be avoided
 */
public static void adjustRectToAvoidIntersection(Rect rectToModify, Rect otherRect) {
  /*
   * Some rectangles are flipped around (left > right). Make sure we have two Rects free of
   * such pathologies.
   */
  rectToModify.sort();
  otherRect.sort();

  if (rectToModify.contains(otherRect) || !Rect.intersects(rectToModify, otherRect)) {
    return;
  }

  /*
   * Intersect rectToModify with four rects that represent cuts of the entire space along
   * lines defined by the otherRect's edges
   */
  Rect[] cuts = {
    new Rect(rectToModify.left, rectToModify.top, otherRect.left, rectToModify.bottom),
    new Rect(rectToModify.left, rectToModify.top, rectToModify.right, otherRect.top),
    new Rect(otherRect.right, rectToModify.top, rectToModify.right, rectToModify.bottom),
    new Rect(rectToModify.left, otherRect.bottom, rectToModify.right, rectToModify.bottom)
  };

  int maxIntersectingRectArea = 0;
  int indexOfLargestIntersection = -1;
  for (int i = 0; i < cuts.length; i++) {
    if (!isSorted(cuts[i])) {
      continue;
    }
    if (Rect.intersects(cuts[i], rectToModify)) {
      /* Reassign this cut to its intersection with rectToModify */
      int visibleRectArea = cuts[i].width() * cuts[i].height();
      if (visibleRectArea > maxIntersectingRectArea) {
        maxIntersectingRectArea = visibleRectArea;
        indexOfLargestIntersection = i;
      }
    }
  }
  if (maxIntersectingRectArea <= 0) {
    // The rectToModify isn't within any of our cuts, so it's entirely occuled by otherRect.
    rectToModify.setEmpty();
    return;
  }
  rectToModify.set(cuts[indexOfLargestIntersection]);
}
 
Example 16
Source File: DirectionalTraversalStrategy.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Goes through root and its descendant nodes, sorting out the focusable nodes and the container
 * nodes for use in finding focus.
 *
 * @return whether the root is focusable or has focusable children in its hierarchy
 */
private boolean processNodes(AccessibilityNodeInfoCompat root, boolean forceRefresh) {
  if (root == null) {
    return false;
  }

  if (forceRefresh) {
    root.refresh();
  }

  Rect currentRect = new Rect();
  root.getBoundsInScreen(currentRect);

  // Determine if the node is inside mRootRect (within a fudge factor). If it is outside, we
  // will optimize by skipping its entire hierarchy.
  if (!Rect.intersects(currentRect, mRootRectPadded)) {
    return false;
  }

  AccessibilityNodeInfoCompat rootNode = AccessibilityNodeInfoCompat.obtain(root);
  mAllNodes.add(rootNode);

  // When we reach a node that supports web navigation, we traverse using the web navigation
  // actions, so we should not add any of its descendants to the list of focusable nodes.
  if (WebInterfaceUtils.hasNativeWebContent(rootNode)) {
    mFocusables.add(rootNode);
    return true;
  } else {
    boolean isFocusable =
        AccessibilityNodeInfoUtils.shouldFocusNode(rootNode, mSpeakingNodesCache);
    if (isFocusable) {
      mFocusables.add(rootNode);
    }

    boolean hasFocusableDescendants = false;
    int childCount = rootNode.getChildCount();
    for (int i = 0; i < childCount; ++i) {
      AccessibilityNodeInfoCompat child = rootNode.getChild(i);
      if (child != null) {
        hasFocusableDescendants |= processNodes(child, forceRefresh);
        child.recycle();
      }
    }

    if (hasFocusableDescendants) {
      mContainers.add(rootNode);
    }

    return isFocusable || hasFocusableDescendants;
  }
}
 
Example 17
Source File: CompassView.java    From PTVGlass with MIT License 4 votes vote down vote up
/**
 * Draws the pins and text labels for the nearby list of places.
 *
 * @param canvas the {@link Canvas} upon which to draw
 * @param pixelsPerDegree the size, in pixels, of one degree step
 * @param offset the number of pixels to translate the drawing operations by in the horizontal
 *         direction; used because place names are drawn three times to get proper wraparound
 */
private void drawPlaces(Canvas canvas, float pixelsPerDegree, float offset) {
    if (mOrientation.hasLocation() && mNearbyPlaces != null) {
        synchronized (mNearbyPlaces) {
            Location userLocation = mOrientation.getLocation();
            double latitude1 = userLocation.getLatitude();
            double longitude1 = userLocation.getLongitude();

            mAllBounds.clear();

            // Loop over the list of nearby places (those within 10 km of the user's current
            // location), and compute the relative bearing from the user's location to the
            // place's location. This determines the position on the compass view where the
            // pin will be drawn.
            for (Place place : mNearbyPlaces) {
                double latitude2 = place.getLatitude();
                double longitude2 = place.getLongitude();
                float bearing = MathUtils.getBearing(latitude1, longitude1, latitude2,
                        longitude2);

                String name = place.getName();
                double distanceKm = MathUtils.getDistance(latitude1, longitude1, latitude2,
                        longitude2);
                String text = getContext().getResources().getString(
                    R.string.place_text_format, name, mDistanceFormat.format(distanceKm));

                // Measure the text and offset the text bounds to the location where the text
                // will finally be drawn.
                Rect textBounds = new Rect();
                mPlacePaint.getTextBounds(text, 0, text.length(), textBounds);
                textBounds.offsetTo((int) (offset + bearing * pixelsPerDegree
                        + PLACE_PIN_WIDTH / 2 + PLACE_TEXT_MARGIN), canvas.getHeight() / 2
                        - (int) PLACE_TEXT_HEIGHT);

                // Extend the bounds rectangle to include the pin icon and a small margin
                // to the right of the text, for the overlap calculations below.
                textBounds.left -= PLACE_PIN_WIDTH + PLACE_TEXT_MARGIN;
                textBounds.right += PLACE_TEXT_MARGIN;

                // This loop attempts to find the best vertical position for the string by
                // starting at the bottom of the display and checking to see if it overlaps
                // with any other labels that were already drawn. If there is an overlap, we
                // move up and check again, repeating this process until we find a vertical
                // position where there is no overlap, or when we reach the limit on
                // overlapping place names.
                boolean intersects;
                int numberOfTries = 0;
                do {
                    intersects = false;
                    numberOfTries++;
                    textBounds.offset(0, (int) -(PLACE_TEXT_HEIGHT + PLACE_TEXT_LEADING));

                    for (Rect existing : mAllBounds) {
                        if (Rect.intersects(existing, textBounds)) {
                            intersects = true;
                            break;
                        }
                    }
                } while (intersects && numberOfTries <= MAX_OVERLAPPING_PLACE_NAMES);

                // Only draw the string if it would not go high enough to overlap the compass
                // directions. This means some places may not be drawn, even if they're nearby.
                if (numberOfTries <= MAX_OVERLAPPING_PLACE_NAMES) {
                    mAllBounds.add(textBounds);

                    canvas.drawBitmap(mPlaceBitmap, offset + bearing * pixelsPerDegree
                            - PLACE_PIN_WIDTH / 2, textBounds.top + 2, mPaint);
                    canvas.drawText(text,
                            offset + bearing * pixelsPerDegree + PLACE_PIN_WIDTH / 2
                            + PLACE_TEXT_MARGIN, textBounds.top + PLACE_TEXT_HEIGHT,
                            mPlacePaint);
                }
            }
        }
    }
}
 
Example 18
Source File: CustomLayoutManager.java    From CustomViewSets with Apache License 2.0 4 votes vote down vote up
/**
 * 回收不需要的Item,并且将需要显示的Item从缓存中取出
 */
private void recycleAndFillItems(RecyclerView.Recycler recycler, RecyclerView.State state) {
    if (state.isPreLayout()) { // 跳过preLayout,preLayout主要用于支持动画
        return;
    }

    // 当前scroll offset状态下的显示区域
    Rect displayFrame = new Rect(mHorizontalScrollOffset, 0, mHorizontalScrollOffset + getHorizontalSpace(), getVerticalSpace());

    /**
     * 将滑出屏幕的Items回收到Recycle缓存中
     */
    Rect childFrame = new Rect();
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        childFrame.left = getDecoratedLeft(child);
        childFrame.top = getDecoratedTop(child);
        childFrame.right = getDecoratedRight(child);
        childFrame.bottom = getDecoratedBottom(child);
        //如果Item没有在显示区域,就说明需要回收
        if (!Rect.intersects(displayFrame, childFrame)) {
            //回收掉滑出屏幕的View
            removeAndRecycleView(child,recycler);

        }
    }

    //重新显示需要出现在屏幕的子View
    for (int i = 0; i < getItemCount(); i++) {
        if (Rect.intersects(displayFrame, mAllItemsFrames.get(i))) {

            View scrap = recycler.getViewForPosition(i);
            measureChildWithMargins(scrap, 0, 0);
            addView(scrap);

            Rect frame = mAllItemsFrames.get(i);
            //将这个item布局出来
            layoutDecorated(scrap,
                    frame.left - mHorizontalScrollOffset,
                    frame.top,
                    frame.right - mHorizontalScrollOffset,
                    frame.bottom);

        }
    }
}
 
Example 19
Source File: FlowLayoutManager.java    From AndroidLibs with GNU General Public License v3.0 4 votes vote down vote up
private boolean lineVisible(int index) {
	int maxHeightItemIndex = getMaxHeightLayoutPositionInLine(index);
	View maxHeightItem = getChildAt(maxHeightItemIndex);
	return Rect.intersects(new Rect(leftVisibleEdge(), topVisibleEdge(), rightVisibleEdge(), bottomVisibleEdge()),
			new Rect(leftVisibleEdge(), getDecoratedTop(maxHeightItem), rightVisibleEdge(), getDecoratedBottom(maxHeightItem)));
}
 
Example 20
Source File: Letterbox.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public boolean isOverlappingWith(Rect rect) {
    if (getWidth() <= 0 || getHeight() <= 0) {
        return false;
    }
    return Rect.intersects(rect, mLayoutFrame);
}