下面列出了android.util.SparseArray#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
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;
}
@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();
}
}
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);
}
}
}
/**
* 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;
}
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;
}
/**
* 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();
}
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());
}
}
}
/**
* 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;
}
/**
* 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--));
}
}
}
/**
* 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);
}
}
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++;
}
}
/**
* 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;
}
/**
* 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);
}
}
/**
* 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;
}
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();
}
/**
* 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;
}
/**
* 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;
}