下面列出了怎么用android.util.SparseBooleanArray的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
resetRecyclerViewPadding(newConfig.orientation);
if (mAsyncTask != null) return;
int[] positions = mManager.findFirstVisibleItemPositions(null);
SparseBooleanArray selectedItems = mAdapter.getSelectedItemsArray();
ViewHelper.resetSpanCount(mRecyclerView,
getActivity().getResources().getInteger(R.integer.request_column_count));
mAdapter = new RequestAdapter(getActivity(),
CandyBarMainActivity.sMissedApps,
mManager.getSpanCount());
mRecyclerView.setAdapter(mAdapter);
mAdapter.setSelectedItemsArray(selectedItems);
if (positions.length > 0)
mRecyclerView.scrollToPosition(positions[0]);
}
/**
* @param mode Mode for the extractor. One of {@link #MODE_MULTI_PMT}, {@link #MODE_SINGLE_PMT}
* and {@link #MODE_HLS}.
* @param timestampAdjuster A timestamp adjuster for offsetting and scaling sample timestamps.
* @param payloadReaderFactory Factory for injecting a custom set of payload readers.
*/
public TsExtractor(
@Mode int mode,
TimestampAdjuster timestampAdjuster,
TsPayloadReader.Factory payloadReaderFactory) {
this.payloadReaderFactory = Assertions.checkNotNull(payloadReaderFactory);
this.mode = mode;
if (mode == MODE_SINGLE_PMT || mode == MODE_HLS) {
timestampAdjusters = Collections.singletonList(timestampAdjuster);
} else {
timestampAdjusters = new ArrayList<>();
timestampAdjusters.add(timestampAdjuster);
}
tsPacketBuffer = new ParsableByteArray(new byte[BUFFER_SIZE], 0);
trackIds = new SparseBooleanArray();
trackPids = new SparseBooleanArray();
tsPayloadReaders = new SparseArray<>();
continuityCounters = new SparseIntArray();
durationReader = new TsDurationReader();
pcrPid = -1;
resetPayloadReaders();
}
public DeviceIdleJobsController(JobSchedulerService service) {
super(service);
mHandler = new DeviceIdleJobsDelayHandler(mContext.getMainLooper());
// Register for device idle mode changes
mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mLocalDeviceIdleController =
LocalServices.getService(DeviceIdleController.LocalService.class);
mDeviceIdleWhitelistAppIds = mLocalDeviceIdleController.getPowerSaveWhitelistUserAppIds();
mPowerSaveTempWhitelistAppIds =
mLocalDeviceIdleController.getPowerSaveTempWhitelistAppIds();
mDeviceIdleUpdateFunctor = new DeviceIdleUpdateFunctor();
mAllowInIdleJobs = new ArraySet<>();
mForegroundUids = new SparseBooleanArray();
final IntentFilter filter = new IntentFilter();
filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
filter.addAction(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
filter.addAction(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
filter.addAction(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
mContext.registerReceiverAsUser(
mBroadcastReceiver, UserHandle.ALL, filter, null, null);
}
@Override
public void onDelete() {
ZogUtils.printLog(MyPMFragment.class, "mListView.getCheckedItemCount():" + mListView.getCheckedItemCount());
if (mListView.getCheckedItemCount() < 1) {
return;
}
int headerCount = mListView.getRefreshableView().getHeaderViewsCount();
SparseBooleanArray array = mListView.getChoicePostions();
int count = mAdapter.getCount();
StringBuffer sb = new StringBuffer();
for (int i = headerCount; i < count + headerCount; i++) {
if (array.get(i)) {
Mypm mypm = (Mypm) mAdapter.getItem(i - headerCount);
if (mypm != null && !TextUtils.isEmpty(mypm.getTouid())) {
sb.append(mypm.getTouid()).append("_");
}
}
}
doDelete(sb.toString(), mAdapter, null);
}
@Override
public void onDelete() {
ZogUtils.printLog(MyPMFragment.class, "mListView.getCheckedItemCount():" + mListView.getCheckedItemCount());
if (mListView.getCheckedItemCount() < 1) {
return;
}
int headerCount = mListView.getRefreshableView().getHeaderViewsCount();
SparseBooleanArray array = mListView.getChoicePostions();
int count = mAdapter.getCount();
StringBuffer sb = new StringBuffer();
for (int i = headerCount; i < count + headerCount; i++) {
if (array.get(i)) {
Mypm mypm = (Mypm) mAdapter.getItem(i - headerCount);
if (mypm != null && !TextUtils.isEmpty(mypm.getTouid())) {
sb.append(mypm.getTouid()).append("_");
}
}
}
doDelete(sb.toString(), mAdapter, null);
}
public void deleteRows(){
//get Selected items
SparseBooleanArray selected = notesAdapter.getmSelectedItems();
//loop through selected items
for (int i = (selected.size()-1) ;i >=0 ; i--){
if (selected.valueAt(i)){
//If the current id is selected remove the item via key
deleteFromNoteRealm(selected.keyAt(i));
notesAdapter.notifyDataSetChanged();
}
}
// Toast.makeText(getContext(), selected.size() + " items deleted", Toast.LENGTH_SHORT).show();
Snackbar snackbar = Snackbar.make(recyclerView,selected.size() + " Notes deleted",Snackbar.LENGTH_SHORT);
snackbar.show();
actionMode.finish();
}
/**
* @return whether the given task should be considered active.
*/
private boolean isActiveRecentTask(TaskRecord task, SparseBooleanArray quietProfileUserIds) {
if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task
+ " globalMax=" + mGlobalMaxNumTasks);
if (quietProfileUserIds.get(task.userId)) {
// Quiet profile user's tasks are never active
if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\tisQuietProfileTask=true");
return false;
}
if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.taskId) {
// Keep the task active if its affiliated task is also active
final TaskRecord affiliatedTask = getTask(task.mAffiliatedTaskId);
if (affiliatedTask != null) {
if (!isActiveRecentTask(affiliatedTask, quietProfileUserIds)) {
if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
"\taffiliatedWithTask=" + affiliatedTask + " is not active");
return false;
}
}
}
// All other tasks are considered active
return true;
}
private Parameters() {
this(
/* selectionOverrides= */ new SparseArray<>(),
/* rendererDisabledFlags= */ new SparseBooleanArray(),
/* preferredAudioLanguage= */ null,
/* preferredTextLanguage= */ null,
/* selectUndeterminedTextLanguage= */ false,
/* disabledTextTrackSelectionFlags= */ 0,
/* forceLowestBitrate= */ false,
/* allowMixedMimeAdaptiveness= */ false,
/* allowNonSeamlessAdaptiveness= */ true,
/* maxVideoWidth= */ Integer.MAX_VALUE,
/* maxVideoHeight= */ Integer.MAX_VALUE,
/* maxVideoBitrate= */ Integer.MAX_VALUE,
/* exceedVideoConstraintsIfNecessary= */ true,
/* exceedRendererCapabilitiesIfNecessary= */ true,
/* viewportWidth= */ Integer.MAX_VALUE,
/* viewportHeight= */ Integer.MAX_VALUE,
/* viewportOrientationMayChange= */ true,
/* tunnelingAudioSessionId= */ C.AUDIO_SESSION_ID_UNSET);
}
@Override
public BuildConfig.ORM[] getSelectedValues() {
final BuildConfig.ORM[] orms = BuildConfig.ORM.values();
final SparseBooleanArray array = getSelectedPositions();
final List<BuildConfig.ORM> list = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
if (array.valueAt(i)) {
list.add(orms[array.keyAt(i)]);
}
}
final BuildConfig.ORM[] selected = new BuildConfig.ORM[list.size()];
list.toArray(selected);
return selected;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
mListener.onDestroyActionMode(actionMode);
// Clear all the checked items
SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions();
if (checkedPositions != null) {
for (int i = 0; i < checkedPositions.size(); i++) {
mListView.setItemChecked(checkedPositions.keyAt(i), false);
}
}
// Restore the original onItemClickListener
mListView.setOnItemClickListener(mOldItemClickListener);
// Clear the Action Mode
mActionMode = null;
// Reset the ListView's Choice Mode
mListView.post(mSetChoiceModeNoneRunnable);
}
/**
* Use this when an item has been deleted, to move the check state of all
* following items up one step. If you have a choiceMode which is not none,
* this method must be called when the order of items changes in an
* underlying adapter which does not have stable IDs (see
* {@link ListAdapter#hasStableIds()}). This is because without IDs, the
* ListView has no way of knowing which items have moved where, and cannot
* update the check state accordingly.
*
* See also further comments on {@link #moveCheckState(int, int)}.
*
* @param position
*/
public void removeCheckState(int position) {
SparseBooleanArray cip = getCheckedItemPositions();
if (cip.size() == 0)
return;
int[] runStart = new int[cip.size()];
int[] runEnd = new int[cip.size()];
int rangeStart = position;
int rangeEnd = cip.keyAt(cip.size() - 1) + 1;
int runCount = buildRunList(cip, rangeStart, rangeEnd, runStart, runEnd);
for (int i = 0; i != runCount; i++) {
if (!(runStart[i] == position || (runEnd[i] < runStart[i] && runEnd[i] > position))) {
// Only set a new check mark in front of this run if it does
// not contain the deleted position. If it does, we only need
// to make it one check mark shorter at the end.
setItemChecked(rotate(runStart[i], -1, rangeStart, rangeEnd),
true);
}
setItemChecked(rotate(runEnd[i], -1, rangeStart, rangeEnd), false);
}
}
private int[] getSelectedIndices(ListView listView) {
SparseBooleanArray sparseArray = listView.getCheckedItemPositions();
int selectedCount = 0;
for (int i = 0; i < sparseArray.size(); ++i) {
if (sparseArray.valueAt(i)) {
selectedCount++;
}
}
int[] indices = new int[selectedCount];
for (int i = 0, j = 0; i < sparseArray.size(); ++i) {
if (sparseArray.valueAt(i)) {
indices[j++] = sparseArray.keyAt(i);
}
}
return indices;
}
/**
* When swapping items the checked item positions in the list may need to be updated
* @param originalPosition
* @param newPosition
*/
private void updateCheckedItemPositions(int originalPosition, int newPosition) {
switch (getChoiceMode()) {
case CHOICE_MODE_SINGLE:
int checkPos = getCheckedItemPosition();
if (checkPos == newPosition) {
setItemChecked(originalPosition, true);
} else if (checkPos == originalPosition) {
setItemChecked(newPosition, false);
}
break;
case CHOICE_MODE_MULTIPLE:
SparseBooleanArray checkedItems = getCheckedItemPositions();
setItemChecked(originalPosition, checkedItems.get(newPosition));
setItemChecked(newPosition, checkedItems.get(originalPosition));
}
}
/**
* @param mode Mode for the extractor. One of {@link #MODE_MULTI_PMT}, {@link #MODE_SINGLE_PMT}
* and {@link #MODE_HLS}.
* @param timestampAdjuster A timestamp adjuster for offsetting and scaling sample timestamps.
* @param payloadReaderFactory Factory for injecting a custom set of payload readers.
*/
public TsExtractor(
@Mode int mode,
TimestampAdjuster timestampAdjuster,
TsPayloadReader.Factory payloadReaderFactory) {
this.payloadReaderFactory = Assertions.checkNotNull(payloadReaderFactory);
this.mode = mode;
if (mode == MODE_SINGLE_PMT || mode == MODE_HLS) {
timestampAdjusters = Collections.singletonList(timestampAdjuster);
} else {
timestampAdjusters = new ArrayList<>();
timestampAdjusters.add(timestampAdjuster);
}
tsPacketBuffer = new ParsableByteArray(new byte[BUFFER_SIZE], 0);
trackIds = new SparseBooleanArray();
trackPids = new SparseBooleanArray();
tsPayloadReaders = new SparseArray<>();
continuityCounters = new SparseIntArray();
durationReader = new TsDurationReader();
pcrPid = -1;
resetPayloadReaders();
}
/**
* Use this when an item has been deleted, to move the check state of all
* following items up one step. If you have a choiceMode which is not none,
* this method must be called when the order of items changes in an
* underlying adapter which does not have stable IDs (see
* {@link android.widget.ListAdapter#hasStableIds()}). This is because without IDs, the
* ListView has no way of knowing which items have moved where, and cannot
* update the check state accordingly.
*
* See also further comments on {@link #moveCheckState(int, int)}.
*
* @param position
*/
public void removeCheckState(int position) {
SparseBooleanArray cip = getCheckedItemPositions();
if (cip.size() == 0)
return;
int[] runStart = new int[cip.size()];
int[] runEnd = new int[cip.size()];
int rangeStart = position;
int rangeEnd = cip.keyAt(cip.size() - 1) + 1;
int runCount = buildRunList(cip, rangeStart, rangeEnd, runStart, runEnd);
for (int i = 0; i != runCount; i++) {
if (!(runStart[i] == position || (runEnd[i] < runStart[i] && runEnd[i] > position))) {
// Only set a new check mark in front of this run if it does
// not contain the deleted position. If it does, we only need
// to make it one check mark shorter at the end.
setItemChecked(rotate(runStart[i], -1, rangeStart, rangeEnd), true);
}
setItemChecked(rotate(runEnd[i], -1, rangeStart, rangeEnd), false);
}
}
private ArrayList<Forum> getDeletedForums() {
final SparseBooleanArray array = mListView.getChoicePostions();
final int headers = mListView.getRefreshableView().getHeaderViewsCount();
final int count = mAdapter.getCount();
final ArrayList<Forum> forums = new ArrayList<Forum>();
for (int i = headers; i < count + headers; i++) {
if (array.get(i)) {
Forum forum = (Forum) mAdapter.getItem(i-headers);
forums.add(forum);
}
}
return forums;
}
private long[] getChecked(SparseBooleanArray array) {
ArrayList<Long> checked = new ArrayList<Long>();
for (int i = 0; i < array.size(); i++) {
int key = array.keyAt(i);
if (array.get(key)) {
checked.add(trackIds[key]);
}
}
long[] result = new long[checked.size()];
for (int i = 0; i < checked.size(); i++) {
result[i] = checked.get(i).longValue();
}
return result;
}
@Override
protected Dialog createDialog() {
loadData();
return new AlertDialog.Builder(getActivity()).setMultiChoiceItems(items, checkedItems, null)
.setNegativeButton(R.string.generic_cancel, null)
.setPositiveButton(R.string.menu_play, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SparseBooleanArray array = ((AlertDialog) dialog).getListView()
.getCheckedItemPositions();
caller.onPlayMultipleDone(getChecked(array));
}
}).setTitle(R.string.menu_play_multiple).create();
}
private static boolean addUidToArray(SparseBooleanArray array, int uid) {
if (UserHandle.isCore(uid)) {
return false;
}
if (array.get(uid)) {
return false;
}
array.put(uid, true);
return true;
}
private static int findFirstSetIndex(@NonNull SparseBooleanArray sba, int rangeStart, int rangeEnd) {
int size = sba.size();
int i = insertionIndexForKey(sba, rangeStart);
while (i < size && sba.keyAt(i) < rangeEnd && !sba.valueAt(i))
i++;
if (i == size || sba.keyAt(i) >= rangeEnd)
return -1;
return i;
}
@Override
void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (isMultiChoiceList()) {
ListAdapter adapter = choicesList.getAdapter();
boolean[] checkedStates = new boolean[adapter.getCount()];
SparseBooleanArray checkedPositions = choicesList.getCheckedItemPositions();
for (int i = 0; i < checkedPositions.size(); i++) {
if (checkedPositions.valueAt(i)) {
checkedStates[checkedPositions.keyAt(i)] = true;
}
}
outState.putBooleanArray(KEY_ITEM_CHECKED_STATES, checkedStates);
}
}
public void deleteSelectedItems() {
SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
adapter.setNotifiable(false);
for (int i = adapter.getCount() - 1; i > -1; i--) {
if (checkedItems.get(i)) {
ExtractionWord extractionWord = adapter.removeItem(i);
extractionWord.delete();
}
}
adapter.setNotifiable(true);
adapter.notifyDataSetChanged();
updateListView();
}
private FakeExtractorInput(byte[] data, boolean simulateUnknownLength,
boolean simulatePartialReads, boolean simulateIOErrors) {
this.data = data;
this.simulateUnknownLength = simulateUnknownLength;
this.simulatePartialReads = simulatePartialReads;
this.simulateIOErrors = simulateIOErrors;
partiallySatisfiedTargetPositions = new SparseBooleanArray();
failedReadPositions = new SparseBooleanArray();
failedPeekPositions = new SparseBooleanArray();
}
public static final String toString(final SparseBooleanArray pSparseBooleanArray) {
final StringBuilder stringBuilder = new StringBuilder();
final int size = pSparseBooleanArray.size();
stringBuilder.append('{');
for (int i = 0; i < size; i++) {
stringBuilder.append(pSparseBooleanArray.keyAt(i)).append('=').append(pSparseBooleanArray.valueAt(i));
if (i < (size - 1)) {
stringBuilder.append(", ");
}
}
stringBuilder.append('}');
return stringBuilder.toString();
}
private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
while (N > 0) {
int key = readInt();
boolean value = this.readByte() == 1;
//Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
outVal.append(key, value);
N--;
}
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A new array which contains the id of each checked item in the
* list.
*
* @deprecated Use {@link #getCheckedItemIds()} instead.
*/
@Deprecated
public long[] getCheckItemIds() {
// Use new behavior that correctly handles stable ID mapping.
if (mAdapter != null && mAdapter.hasStableIds()) {
return getCheckedItemIds();
}
// Old behavior was buggy, but would sort of work for adapters without stable IDs.
// Fall back to it to support legacy apps.
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
final SparseBooleanArray states = mCheckStates;
final int count = states.size();
final long[] ids = new long[count];
final ListAdapter adapter = mAdapter;
int checkedCount = 0;
for (int i = 0; i < count; i++) {
if (states.valueAt(i)) {
ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
}
}
// Trim array if needed. mCheckStates may contain false values
// resulting in checkedCount being smaller than count.
if (checkedCount == count) {
return ids;
} else {
final long[] result = new long[checkedCount];
System.arraycopy(ids, 0, result, 0, checkedCount);
return result;
}
}
return new long[0];
}
/**
* Gets the position of the one and only checked item in the provided list in multiple selection
* mode.
*
* @return {@code 0}-based position.
* @throws IllegalStateException if the list is not in multiple selection mode, or if the number
* of checked items is not {@code 1}.
*/
@TargetApi(11)
private static int getMultiSelectListSingleCheckedItemPosition(AbsListView list) {
Preconditions.checkState(list.getCheckedItemCount() == 1);
SparseBooleanArray checkedItemPositions = list.getCheckedItemPositions();
Preconditions.checkState(checkedItemPositions != null);
for (int i = 0, len = list.getCount(); i < len; i++) {
boolean itemChecked = checkedItemPositions.get(i);
if (itemChecked) {
return i;
}
}
throw new IllegalStateException("No items checked");
}
private Parameters() {
this(
// Video
/* maxVideoWidth= */ Integer.MAX_VALUE,
/* maxVideoHeight= */ Integer.MAX_VALUE,
/* maxVideoFrameRate= */ Integer.MAX_VALUE,
/* maxVideoBitrate= */ Integer.MAX_VALUE,
/* exceedVideoConstraintsIfNecessary= */ true,
/* allowVideoMixedMimeTypeAdaptiveness= */ false,
/* allowVideoNonSeamlessAdaptiveness= */ true,
/* viewportWidth= */ Integer.MAX_VALUE,
/* viewportHeight= */ Integer.MAX_VALUE,
/* viewportOrientationMayChange= */ true,
// Audio
TrackSelectionParameters.DEFAULT.preferredAudioLanguage,
/* maxAudioChannelCount= */ Integer.MAX_VALUE,
/* maxAudioBitrate= */ Integer.MAX_VALUE,
/* exceedAudioConstraintsIfNecessary= */ true,
/* allowAudioMixedMimeTypeAdaptiveness= */ false,
/* allowAudioMixedSampleRateAdaptiveness= */ false,
/* allowAudioMixedChannelCountAdaptiveness= */ false,
// Text
TrackSelectionParameters.DEFAULT.preferredTextLanguage,
TrackSelectionParameters.DEFAULT.preferredTextRoleFlags,
TrackSelectionParameters.DEFAULT.selectUndeterminedTextLanguage,
TrackSelectionParameters.DEFAULT.disabledTextTrackSelectionFlags,
// General
/* forceLowestBitrate= */ false,
/* forceHighestSupportedBitrate= */ false,
/* exceedRendererCapabilitiesIfNecessary= */ true,
/* tunnelingAudioSessionId= */ C.AUDIO_SESSION_ID_UNSET,
new SparseArray<>(),
new SparseBooleanArray());
}
private static boolean areRendererDisabledFlagsEqual(
SparseBooleanArray first, SparseBooleanArray second) {
int firstSize = first.size();
if (second.size() != firstSize) {
return false;
}
// Only true values are put into rendererDisabledFlags, so we don't need to compare values.
for (int indexInFirst = 0; indexInFirst < firstSize; indexInFirst++) {
if (second.indexOfKey(first.keyAt(indexInFirst)) < 0) {
return false;
}
}
return true;
}
public void setText(@Nullable CharSequence text, @NonNull SparseBooleanArray collapsedStatus, int position) {
mCollapsedStatus = collapsedStatus;
mPosition = position;
boolean isCollapsed = collapsedStatus.get(position, true);
clearAnimation();
mCollapsed = isCollapsed;
mExpandIndicatorController.changeState(mCollapsed);
setText(text);
}