android.util.SparseArray#size ( )源码实例Demo

下面列出了android.util.SparseArray#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Shield   文件: TopLinearLayoutManager.java
@Override
public int findFirstCompletelyVisibleItemPosition() {
    if (enableTop && currentTopViewList != null && currentTopViewList.size() > 0) {
        SparseArray<View> viewSparseArray = findItemPositionArray();
        for (int i = 0; i < viewSparseArray.size(); i++) {
            View view = viewSparseArray.valueAt(i);
            if (mOrientationHelper.getDecoratedMeasurement(view) <= 0) {
                continue;
            }
            int pos = viewSparseArray.keyAt(i);
            if (currentTopViewList.indexOfKey(pos) < 0) {
                if (pos < currentTopViewList.keyAt(0)) {
                    if (view.getTop() >= 0) { // 这里认为是view本身全部露出视为completelyVisible,而不是是view+decoration+margin
                        return pos;
                    }
                } else {
                    return fixFirstVisibleItem(pos, true);
                }
            }
        }
    }

    return super.findFirstCompletelyVisibleItemPosition();
}
 
/**
 * Returns a string composed from a {@link SparseArray}.
 */
static String toString(@Nullable final SparseArray<byte[]> array) {
	if (array == null) {
		return "null";
	}
	if (array.size() == 0) {
		return "{}";
	}
	final StringBuilder buffer = new StringBuilder();
	buffer.append('{');
	for (int i = 0; i < array.size(); ++i) {
		buffer.append(array.keyAt(i)).append("=").append(Arrays.toString(array.valueAt(i)));
	}
	buffer.append('}');
	return buffer.toString();
}
 
源代码3 项目: UltimateAndroid   文件: Recycler.java
static Scrap retrieveFromScrap(SparseArray<Scrap> scrapViews, int position) {
	int size = scrapViews.size();
	if (size > 0) {
		// See if we still have a view for this position.
		Scrap result = scrapViews.get(position, null);
		if (result != null) {
			scrapViews.remove(position);
			return result;
		}
		int index = size - 1;
		result = scrapViews.valueAt(index);
		scrapViews.removeAt(index);
		result.valid = false;
		return result;
	}
	return null;
}
 
源代码4 项目: budget-envelopes   文件: PaycheckFragment.java
@Override public void ok() {
    SparseArray<Long> deposites = mEnvelopes.getDeposites();
    String description = mDescription.getText().toString();
    String frequency = null;
    int l = deposites.size();
    SQLiteDatabase db = (new EnvelopesOpenHelper(getActivity())).getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        for (int i = 0; i != l; ++i) {
            int id = deposites.keyAt(i);
            long centsDeposited = deposites.valueAt(i);
            EnvelopesOpenHelper.deposite(db, id, centsDeposited, description, frequency);
            values.put("lastPaycheckCents", centsDeposited);
            db.update("envelopes", values, "_id = ?", new String[] {
                Integer.toString(id)
            });
        }
        db.setTransactionSuccessful();
        getActivity().getContentResolver().notifyChange(EnvelopesOpenHelper.URI, null);
    } finally {
        db.endTransaction();
        db.close();
    }
}
 
源代码5 项目: MediaSDK   文件: DefaultTrackSelector.java
private static void writeSelectionOverridesToParcel(
    Parcel dest,
    SparseArray<Map<TrackGroupArray, @NullableType SelectionOverride>> selectionOverrides) {
  int renderersWithOverridesCount = selectionOverrides.size();
  dest.writeInt(renderersWithOverridesCount);
  for (int i = 0; i < renderersWithOverridesCount; i++) {
    int rendererIndex = selectionOverrides.keyAt(i);
    Map<TrackGroupArray, @NullableType SelectionOverride> overrides =
        selectionOverrides.valueAt(i);
    int overrideCount = overrides.size();
    dest.writeInt(rendererIndex);
    dest.writeInt(overrideCount);
    for (Map.Entry<TrackGroupArray, @NullableType SelectionOverride> override :
        overrides.entrySet()) {
      dest.writeParcelable(override.getKey(), /* parcelableFlags= */ 0);
      dest.writeParcelable(override.getValue(), /* parcelableFlags= */ 0);
    }
  }
}
 
源代码6 项目: TelePlus-Android   文件: FragmentedMp4Extractor.java
/**
 * Returns the {@link TrackBundle} whose fragment run has the earliest file position out of those
 * yet to be consumed, or null if all have been consumed.
 */
private static TrackBundle getNextFragmentRun(SparseArray<TrackBundle> trackBundles) {
  TrackBundle nextTrackBundle = null;
  long nextTrackRunOffset = Long.MAX_VALUE;

  int trackBundlesSize = trackBundles.size();
  for (int i = 0; i < trackBundlesSize; i++) {
    TrackBundle trackBundle = trackBundles.valueAt(i);
    if (trackBundle.currentTrackRunIndex == trackBundle.fragment.trunCount) {
      // This track fragment contains no more runs in the next mdat box.
    } else {
      long trunOffset = trackBundle.fragment.trunDataPosition[trackBundle.currentTrackRunIndex];
      if (trunOffset < nextTrackRunOffset) {
        nextTrackBundle = trackBundle;
        nextTrackRunOffset = trunOffset;
      }
    }
  }
  return nextTrackBundle;
}
 
源代码7 项目: android_9.0.0_r45   文件: LegacyCameraDevice.java
static List<Long> getSurfaceIds(SparseArray<Surface> surfaces)
        throws BufferQueueAbandonedException {
    if (surfaces == null) {
        throw new NullPointerException("Null argument surfaces");
    }
    List<Long> surfaceIds = new ArrayList<>();
    int count = surfaces.size();
    for (int i = 0; i < count; i++) {
        long id = getSurfaceId(surfaces.valueAt(i));
        if (id == 0) {
            throw new IllegalStateException(
                    "Configured surface had null native GraphicBufferProducer pointer!");
        }
        surfaceIds.add(id);
    }
    return surfaceIds;
}
 
源代码8 项目: AndroidBleManager   文件: ByteUtils.java
/**
 * Returns a string composed from a {@link SparseArray}.
 */
public static String toString(SparseArray<byte[]> array) {
    if (array == null) {
        return "null";
    }
    if (array.size() == 0) {
        return "{}";
    }
    StringBuilder buffer = new StringBuilder();
    buffer.append('{');
    for (int i = 0; i < array.size(); ++i) {
        buffer.append(array.keyAt(i)).append("=").append(array.valueAt(i));
    }
    buffer.append('}');
    return buffer.toString();
}
 
源代码9 项目: text-detector   文件: MainActivity.java
public void detectText(View view) {
    Bitmap textBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cat);

    TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();

    if (!textRecognizer.isOperational()) {
        new AlertDialog.Builder(this)
                .setMessage("Text recognizer could not be set up on your device :(")
                .show();
        return;
    }

    Frame frame = new Frame.Builder().setBitmap(textBitmap).build();
    SparseArray<TextBlock> text = textRecognizer.detect(frame);

    for (int i = 0; i < text.size(); ++i) {
        TextBlock item = text.valueAt(i);
        if (item != null && item.getValue() != null) {
            detectedTextView.setText(item.getValue());
        }
    }
}
 
源代码10 项目: K-Sonic   文件: FragmentedMp4Extractor.java
/**
 * Returns the {@link TrackBundle} whose fragment run has the earliest file position out of those
 * yet to be consumed, or null if all have been consumed.
 */
private static TrackBundle getNextFragmentRun(SparseArray<TrackBundle> trackBundles) {
  TrackBundle nextTrackBundle = null;
  long nextTrackRunOffset = Long.MAX_VALUE;

  int trackBundlesSize = trackBundles.size();
  for (int i = 0; i < trackBundlesSize; i++) {
    TrackBundle trackBundle = trackBundles.valueAt(i);
    if (trackBundle.currentTrackRunIndex == trackBundle.fragment.trunCount) {
      // This track fragment contains no more runs in the next mdat box.
    } else {
      long trunOffset = trackBundle.fragment.trunDataPosition[trackBundle.currentTrackRunIndex];
      if (trunOffset < nextTrackRunOffset) {
        nextTrackBundle = trackBundle;
        nextTrackRunOffset = trunOffset;
      }
    }
  }
  return nextTrackBundle;
}
 
源代码11 项目: Noyze   文件: RecycleBin.java
/**
 * Makes sure that the size of scrapViews does not exceed the size of activeViews.
 * (This can happen if an adapter does not recycle its views).
 */
private void pruneScrapViews() {
    final int maxViews = activeViews.length;
    final int viewTypeCount = this.viewTypeCount;
    final SparseArray<View>[] scrapViews = this.scrapViews;
    for (int i = 0; i < viewTypeCount; ++i) {
        final SparseArray<View> scrapPile = scrapViews[i];
        int size = scrapPile.size();
        final int extras = size - maxViews;
        size--;
        for (int j = 0; j < extras; j++) {
            scrapPile.remove(scrapPile.keyAt(size--));
        }
    }
}
 
源代码12 项目: alpha-wallet-android   文件: GasSliderView.java
/**
 * This method will check for current progress and validate in which gap it is falling.
 * Based on the falling price range, it will take the estimated time factor.
 */
private void updateTimings()
{
    if(gasTransactionResponse != null) {
        float correctedPrice = gasPrice.getValue().floatValue() * 10.0f;
        String estimatedTime = "";
        SparseArray<Float> priceRange = gasTransactionResponse.getResult(); //use SparseArray as you get automatically sorted contents

        float minutes = 0;

        //Extrapolate between adjacent price readings
        for (int index = 0; index < priceRange.size() - 1; index++)
        {
            int lowerBound = priceRange.keyAt(index);
            int upperBound = priceRange.keyAt(index + 1);
            if (lowerBound <= correctedPrice && upperBound >= correctedPrice)
            {
                float timeDiff = priceRange.get(lowerBound) - priceRange.get(upperBound);
                float extrapolateFactor = (correctedPrice - (float)lowerBound)/(float)(upperBound - lowerBound);
                minutes = priceRange.get(lowerBound) - extrapolateFactor * timeDiff;
                break;
            }
        }

        if (correctedPrice > priceRange.keyAt(priceRange.size() - 1)) minutes = priceRange.valueAt(priceRange.size() - 1);

        estimatedTime = convertGasEstimatedTime((int)(minutes * 60.0f));
        estimateTimeValue.setText(estimatedTime);
    }
}
 
源代码13 项目: ParcelableGenerator   文件: ParcelUtil.java
private static void writeSparseArray(Parcel dest, SparseArray<Object> val) {
    if (val == null) {
        dest.writeInt(-1);
        return;
    }
    int N = val.size();
    dest.writeInt(N);
    int i = 0;
    while (i < N) {
        dest.writeInt(val.keyAt(i));
        writeValue(dest, val.valueAt(i));
        i++;
    }
}
 
源代码14 项目: Roundr   文件: WindowCache.java
/**
 * Returns the ids in the {@link #sWindows} cache.
 * 
 * @param cls
 *            The class of the implementation of the window.
 * @return The ids representing the cached windows.
 */
public Set<Integer> getCacheIds(Class<? extends StandOutWindow> cls) {
	SparseArray<Window> l2 = sWindows.get(cls);
	if (l2 == null) {
		return new HashSet<Integer>();
	}

	Set<Integer> keys = new HashSet<Integer>();
	for (int i = 0; i < l2.size(); i++) {
		keys.add(l2.keyAt(i));
	}
	return keys;
}
 
源代码15 项目: Document-Scanner   文件: OcrDetectorProcessor.java
/**
 * Called by the detector to deliver detection results.
 * If your application called for it, this could be a place to check for
 * equivalent detections by tracking TextBlocks that are similar in lo
 * ion and content from
 * previous frames, or reduce noise by eliminating TextBlocks that have not persisted through
 * multiple detections.
 */
@Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
    mGraphicOverlay.clear();
    SparseArray<TextBlock> items = detections.getDetectedItems();
    for (int i = 0; i < items.size(); ++i) {
        TextBlock item = items.valueAt(i);
        OcrGraphic graphic = new OcrGraphic(mGraphicOverlay, item);
        mGraphicOverlay.add(graphic);
    }
}
 
源代码16 项目: LogcatViewer   文件: WindowCache.java
/**
 * Returns the ids in the {@link #sWindows} cache.
 * 
 * @param cls
 *            The class of the implementation of the window.
 * @return The ids representing the cached windows.
 */
public Set<Integer> getCacheIds(Class<? extends StandOutWindow> cls) {
	SparseArray<Window> l2 = sWindows.get(cls);
	if (l2 == null) {
		return new HashSet<Integer>();
	}

	Set<Integer> keys = new HashSet<Integer>();
	for (int i = 0; i < l2.size(); i++) {
		keys.add(l2.keyAt(i));
	}
	return keys;
}
 
源代码17 项目: android-apps   文件: IcsAbsSpinner.java
void clear() {
    final SparseArray<View> scrapHeap = mScrapHeap;
    final int count = scrapHeap.size();
    for (int i = 0; i < count; i++) {
        final View view = scrapHeap.valueAt(i);
        if (view != null) {
            removeDetachedView(view, true);
        }
    }
    scrapHeap.clear();
}
 
源代码18 项目: AndroidBleManager   文件: AdRecordStore.java
/**
 * As list.
 *
 * @param <C>         the generic type
 * @param sparseArray the sparse array
 * @return the collection
 */
public static <C> Collection<C> asList(final SparseArray<C> sparseArray) {
    if (sparseArray == null) return null;

    final Collection<C> arrayList = new ArrayList<>(sparseArray.size());
    for (int i = 0; i < sparseArray.size(); i++) {
        arrayList.add(sparseArray.valueAt(i));
    }

    return arrayList;
}
 
源代码19 项目: LogcatViewer   文件: WindowCache.java
/**
 * Remove the window corresponding to the id from the {@link #sWindows}
 * cache.
 * 
 * @param id
 *            The id representing the window.
 * @param cls
 *            The class of the implementation of the window.
 */
public void removeCache(int id, Class<? extends StandOutWindow> cls) {
	SparseArray<Window> l2 = sWindows.get(cls);
	if (l2 != null) {
		l2.remove(id);
		if (l2.size() == 0) {
			sWindows.remove(cls);
		}
	}
}
 
List<String> getRow(int rowIndex) {
        List<String> result = new ArrayList<>();

        // cache logic. Show field after not saved changes
        List<String> cachedRow = mItemsCache.get(rowIndex);
        if (cachedRow != null && !cachedRow.isEmpty()) {
            SparseArray<String> changedRow = mChangedItems.get(rowIndex);
            if (changedRow != null && changedRow.size() > 0) {
                for (int count = cachedRow.size(), i = 0; i < count; i++) {
                    String cachedItem = cachedRow.get(i);
                    String changedItem = changedRow.get(i);
                    result.add(TextUtils.isEmpty(changedItem) ? cachedItem : changedItem);
                }
            } else {
                result.addAll(cachedRow);
            }
        }


        if (!result.isEmpty()) {
            return result;
        }

        //read from file
        InputStreamReader fileReader = null;

        try {
            fileReader = getInputStreamReader();
            int cacheRowIndex = rowIndex < READ_FILE_LINES_LIMIT ? 0 : rowIndex - READ_FILE_LINES_LIMIT;
            //skip upper lines
            Scanner scanner = new Scanner(fileReader).skip("(?:.*\\r?\\n|\\r){" + cacheRowIndex + "}");

//            for (int i = 0; i < cacheRowIndex; i++) {
//                scanner.nextLine();
//            }

            int cacheRowLimitIndex = cacheRowIndex + READ_FILE_LINES_LIMIT + READ_FILE_LINES_LIMIT;
            //on scroll to bottom
            for (int i = cacheRowIndex; i < getRowsCount() && i < cacheRowLimitIndex && scanner.hasNextLine(); i++) {
                List<String> line = new ArrayList<>(CsvUtils.parseLine(scanner.nextLine()));
                mItemsCache.put(i, line);
                if (i == rowIndex) {
                    result.addAll(line);
                }
            }

            // clear cache
            Iterator<Map.Entry<Integer, List<String>>> iterator = mItemsCache.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Integer, List<String>> entry = iterator.next();
                if (entry.getKey() < cacheRowIndex || entry.getKey() > cacheRowLimitIndex) {
                    iterator.remove();
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "getRow method error ", e);
        } finally {
            ClosableUtil.closeWithoutException(fileReader);
        }

        return result;
    }