List of usage examples for android.util SparseBooleanArray keyAt
public int keyAt(int index)
0...size()-1
, returns the key from the index
th key-value mapping that this SparseBooleanArray stores. From source file:com.gmail.taneza.ronald.carbs.main.MainActivity.java
private void deleteFromFoodList(ArrayList<FoodItem> foodList, SparseBooleanArray itemsToDelete) { int numItemsToDelete = itemsToDelete.size(); if (itemsToDelete.size() <= 0) { return;// www . ja v a 2s. c o m } if (numItemsToDelete > foodList.size()) { throw new IllegalArgumentException("numItemsToDelete is larger than the foodList size"); } // Each item in 'itemsToDelete' has a key and a value. // The key is an index to 'mFoodItemsList'. // The value is a boolean: true means that the item should be deleted. // Start from the end of the list, because items in the list will be shifted after each 'delete' call. // Keys are guaranteed to be sorted in ascending order, // e.g. keyAt(0) will return the smallest key and keyAt(size()-1) will return the largest key. for (int n = (numItemsToDelete - 1); n >= 0; n--) { int index = itemsToDelete.keyAt(n); if (itemsToDelete.get(index)) { foodList.remove(index); } } updateRecentFoodsAndMealData(); }
From source file:com.todotxt.todotxttouch.TodoTxtTouch.java
private ArrayList<Task> getCheckedTasks() { ArrayList<Task> result = new ArrayList<Task>(); SparseBooleanArray checkedItems = getListView().getCheckedItemPositions(); for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { result.add(m_adapter.getItem(checkedItems.keyAt(i))); }//from w w w . j a v a2 s .c o m } return result; }
From source file:org.totschnig.myexpenses.fragment.CategoryList.java
@Override public boolean dispatchCommandMultiple(int command, SparseBooleanArray positions, Long[] itemIds) { ManageCategories ctx = (ManageCategories) getActivity(); ArrayList<Long> idList; switch (command) { case R.id.DELETE_COMMAND: int mappedTransactionsCount = 0, mappedTemplatesCount = 0, hasChildrenCount = 0; idList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { Cursor c;/*from w w w. ja va2s . c om*/ if (positions.valueAt(i)) { boolean deletable = true; int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int type = ExpandableListView.getPackedPositionType(pos); int group = ExpandableListView.getPackedPositionGroup(pos), child = ExpandableListView.getPackedPositionChild(pos); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { c = mAdapter.getChild(group, child); c.moveToPosition(child); } else { c = mGroupCursor; c.moveToPosition(group); } long itemId = c.getLong(c.getColumnIndex(KEY_ROWID)); Bundle extras = ctx.getIntent().getExtras(); if ((extras != null && extras.getLong(KEY_ROWID) == itemId) || c.getInt(c.getColumnIndex(DatabaseConstants.KEY_MAPPED_TRANSACTIONS)) > 0) { mappedTransactionsCount++; deletable = false; } else if (c.getInt(c.getColumnIndex(DatabaseConstants.KEY_MAPPED_TEMPLATES)) > 0) { mappedTemplatesCount++; deletable = false; } if (deletable) { if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP && c.getInt(c.getColumnIndex(KEY_CHILD_COUNT)) > 0) { hasChildrenCount++; } idList.add(itemId); } } } if (!idList.isEmpty()) { Long[] objectIds = idList.toArray(new Long[idList.size()]); if (hasChildrenCount > 0) { MessageDialogFragment .newInstance(R.string.dialog_title_warning_delete_main_category, getResources().getQuantityString(R.plurals.warning_delete_main_category, hasChildrenCount, hasChildrenCount), new MessageDialogFragment.Button(android.R.string.yes, R.id.DELETE_COMMAND_DO, objectIds), null, new MessageDialogFragment.Button(android.R.string.no, R.id.CANCEL_CALLBACK_COMMAND, null)) .show(ctx.getSupportFragmentManager(), "DELETE_CATEGORY"); } else { ctx.dispatchCommand(R.id.DELETE_COMMAND_DO, objectIds); } } if (mappedTransactionsCount > 0 || mappedTemplatesCount > 0) { String message = ""; if (mappedTransactionsCount > 0) message += getResources().getQuantityString(R.plurals.not_deletable_mapped_transactions, mappedTransactionsCount, mappedTransactionsCount); if (mappedTemplatesCount > 0) message += getResources().getQuantityString(R.plurals.not_deletable_mapped_templates, mappedTemplatesCount, mappedTemplatesCount); Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } return true; case R.id.SELECT_COMMAND_MULTIPLE: ArrayList<String> labelList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { Cursor c; if (positions.valueAt(i)) { int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int type = ExpandableListView.getPackedPositionType(pos); int group = ExpandableListView.getPackedPositionGroup(pos), child = ExpandableListView.getPackedPositionChild(pos); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { c = mAdapter.getChild(group, child); c.moveToPosition(child); } else { c = mGroupCursor; c.moveToPosition(group); } labelList.add(c.getString(c.getColumnIndex(KEY_LABEL))); } } Intent intent = new Intent(); intent.putExtra(KEY_CATID, ArrayUtils.toPrimitive(itemIds)); intent.putExtra(KEY_LABEL, TextUtils.join(",", labelList)); ctx.setResult(ManageCategories.RESULT_FIRST_USER, intent); ctx.finish(); return true; case R.id.MOVE_COMMAND: final Long[] excludedIds; final boolean inGroup = expandableListSelectionType == ExpandableListView.PACKED_POSITION_TYPE_GROUP; if (inGroup) { excludedIds = itemIds; } else { idList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { if (positions.valueAt(i)) { int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int group = ExpandableListView.getPackedPositionGroup(pos); mGroupCursor.moveToPosition(group); idList.add(mGroupCursor.getLong(mGroupCursor.getColumnIndex(KEY_ROWID))); } } excludedIds = idList.toArray(new Long[idList.size()]); } Bundle args = new Bundle(3); args.putBoolean(SelectMainCategoryDialogFragment.KEY_WITH_ROOT, !inGroup); args.putLongArray(SelectMainCategoryDialogFragment.KEY_EXCLUDED_ID, ArrayUtils.toPrimitive(excludedIds)); args.putLongArray(TaskExecutionFragment.KEY_OBJECT_IDS, ArrayUtils.toPrimitive(itemIds)); SelectMainCategoryDialogFragment.newInstance(args).show(getFragmentManager(), "SELECT_TARGET"); return true; } return false; }
From source file:com.bitants.wally.fragments.SavedImagesFragment.java
@Override public boolean onActionItemClicked(final ActionMode mode, MenuItem item) { if (R.id.menu_delete == item.getItemId()) { int size = 0; SparseBooleanArray checkedItems = recyclerSavedImagesAdapter.getSelectedItems(); for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { size++;//from w w w. jav a 2 s .c o m } } String quantityString = getResources().getQuantityString(R.plurals.wallpapers, size); String title = String.format(getString(R.string.dialog_delete_title), quantityString); FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager != null) { final MaterialDialogFragment materialDialogFragment = new MaterialDialogFragment(); materialDialogFragment.setPrimaryColor(getResources().getColor(R.color.Dialog_Button_Delete)); materialDialogFragment.setTitle(title); materialDialogFragment.setPositiveButton(R.string.dialog_delete_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { SparseBooleanArray checkedItems = recyclerSavedImagesAdapter.getSelectedItems(); for (int index = 0; index < checkedItems.size(); index++) { if (checkedItems.valueAt(index)) { Uri contentUri = recyclerSavedImagesAdapter .getItem(checkedItems.keyAt(index)); getActivity().getContentResolver().delete(contentUri, null, null); } } mode.finish(); getImages(0, null); getActivity().sendBroadcast(new Intent(FileReceiver.GET_FILES)); } }); materialDialogFragment.setNegativeButton(R.string.dialog_delete_negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { materialDialogFragment.dismiss(); } }); materialDialogFragment.show(fragmentManager, MaterialDialogFragment.TAG); } } return false; }
From source file:com.musenkishi.wally.fragments.SavedImagesFragment.java
@Override public boolean onActionItemClicked(final ActionMode mode, MenuItem item) { if (R.id.menu_delete == item.getItemId()) { int size = 0; SparseBooleanArray checkedItems = recyclerSavedImagesAdapter.getSelectedItems(); for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { size++;/*from w w w.j ava2 s . c om*/ } } String quantityString = getResources().getQuantityString(R.plurals.wallpapers, size); String title = String.format(getString(R.string.dialog_delete_title), quantityString); FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager != null) { final MaterialDialogFragment materialDialogFragment = new MaterialDialogFragment(); materialDialogFragment.setPrimaryColor(getResources().getColor(R.color.Dialog_Button_Delete)); materialDialogFragment.setTitle(title); materialDialogFragment.setPositiveButton(R.string.dialog_delete_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { SparseBooleanArray checkedItems = recyclerSavedImagesAdapter.getSelectedItems(); for (int index = 0; index < checkedItems.size(); index++) { if (checkedItems.valueAt(index)) { Uri contentUri = recyclerSavedImagesAdapter .getItem(checkedItems.keyAt(index)); getActivity().getContentResolver().delete(contentUri, null, null); } } mode.finish(); getImages(0, null); getActivity().sendBroadcast(new Intent(FileChangeReceiver.FILES_CHANGED)); } }); materialDialogFragment.setNegativeButton(R.string.dialog_delete_negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { materialDialogFragment.dismiss(); } }); materialDialogFragment.show(fragmentManager, MaterialDialogFragment.TAG); } } return false; }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
@NotNull private List<Task> getCheckedTasks() { ArrayList<Task> checkedTasks = new ArrayList<Task>(); SparseBooleanArray checkedItems = getListView().getCheckedItemPositions(); if (checkedItems == null) { return checkedTasks; }/* ww w. j a v a 2 s.co m*/ for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { Task t = getTaskAt(checkedItems.keyAt(i)); // Ignore headers if (t != null) { checkedTasks.add(getTaskAt(checkedItems.keyAt(i))); } } } return checkedTasks; }
From source file:com.tweetlanes.android.core.view.TweetFeedFragment.java
@Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); if (mTwitterStatusIdWhenRefreshed != null) state.putLong("TwitterStatusIdWhenRefreshed", mTwitterStatusIdWhenRefreshed); if (mLastTwitterStatusIdSeen != null) state.putLong("LastTwitterStatusIdSeen", mLastTwitterStatusIdSeen); state.putInt("NewStatuses", mNewStatuses); state.putBoolean("HidingListHeading", mHidingListHeading); mSelectedItems.clear();/*from w ww. j a va 2 s . c om*/ android.util.SparseBooleanArray items = mTweetFeedListView.getRefreshableView().getCheckedItemPositions(); for (int i = 0; i < items.size(); i++) { int key = items.keyAt(i); mTweetFeedListView.getRefreshableView().setItemChecked(key, false); } }
From source file:org.kontalk.ui.AbstractComposeFragment.java
private int getCheckedItemPosition() { SparseBooleanArray checked = getListView().getCheckedItemPositions(); return checked.keyAt(checked.indexOfValue(true)); }
From source file:com.huewu.pla.lib.internal.PLAListView.java
/** * 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}. * /*from w ww.j a v a 2s .com*/ * @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]; }
From source file:net.kazzz.NFCTagWriter.java
/** * ISO15693 Tag????????/* w w w .j a v a 2s. c o m*/ * * * @param btnWrite ????? * @param editWrite ?? * @param listMemBlock? * @param useNDEFNDEF???? */ private void prepareISO15693(final Button btnWrite, final EditText editWrite, final ListView listMemBlock) { final CheckBox chkUseNDEF = (CheckBox) findViewById(R.id.chk_useNDEF); //?? ISO15693Tag ft = new ISO15693Tag(this.mNfcTag); try { SystemInformationResponse sysInfo = ft.getSystemInformation(); if (sysInfo == null || sysInfo.hasError()) { throw new ISO15693Exception( "ISO15693 ??????????? : " + sysInfo.getErrorCode()); } final MemorySizeInfo memInfo = sysInfo.getMemoryInfo(); if (memInfo == null || memInfo.getNumberOfBlocks() == 0) { throw new ISO15693Exception("ISO15693 ?????????"); } chkUseNDEF.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { listMemBlock.setEnabled(!chkUseNDEF.isChecked()); listMemBlock.setClickable(!chkUseNDEF.isChecked()); //NDEF??NDEF????? if (chkUseNDEF.isChecked()) { btnWrite.setEnabled(true); editWrite.setEnabled(true); //NDEF????10byte? editWrite.setHint((memInfo.getBlockSize() * memInfo.getNumberOfBlocks()) - 10 + "??"); } else { if (editWrite.getText().length() > 0) { btnWrite.setEnabled(true); editWrite.setEnabled(true); } else { btnWrite.setEnabled(false); editWrite.setEnabled(false); } editWrite.setHint(memInfo.getBlockSize() + "??"); } } }); ReadMultipleBlocksResponse rbResp = ft.readMultipleBlocks((byte) 0, memInfo.getBlockSize(), memInfo.getNumberOfBlocks()); if (rbResp == null || rbResp.hasError()) { throw new ISO15693Exception( "ISO15693 ReadMultipleBlock?????" + sysInfo.getErrorCode()); } //?????? ViewHolder[] holders = new ViewHolder[memInfo.getNumberOfBlocks()]; for (byte i = 0; i < memInfo.getNumberOfBlocks(); i++) { BlockData bd = rbResp.getBlockDatas()[i]; ViewHolder holder = new ViewHolder(); holder.blockName = "block " + i; holder.isWritable = !bd.isLocked(); holder.accessMode = bd.isLocked() ? "(Lock)" : "(UnLock)"; //?? if (bd.getData() != null && bd.getData().length > 0) { holder.data = bd.getData(); } else { holder.data = new byte[memInfo.getBlockSize()]; for (int b = 0; b < holder.data.length; b++) { holder.data[b] = 0x00; //?? } } holders[i] = holder; } final LayoutInflater layoutInflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); //ArrayAdapter? (?? ArrayAdapter<ViewHolder> adapter = new ArrayAdapter<ViewHolder>(this, android.R.layout.simple_list_item_multiple_choice, holders) { /* (non-Javadoc) * @see android.widget.BaseAdapter#isEnabled(int) */ @Override public boolean isEnabled(int position) { SparseBooleanArray arry = listMemBlock.getCheckedItemPositions(); if (arry.indexOfValue(true) != -1 && !arry.get(position) //??????? && (!arry.get(position - 1) && !arry.get(position + 1))) //????? { //??????? return false; } return super.isEnabled(position); } /* (non-Javadoc) * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { if (null == convertView) { convertView = layoutInflater.inflate(android.R.layout.simple_list_item_multiple_choice, null); } ViewHolder holder = this.getItem(position); if (holder != null) { StringBuilder sb = new StringBuilder(); sb.append(holder.blockName).append(" ").append(holder.accessMode).append("\n"); if (holder.data != null && holder.data.length > 0) { //UTF-8? Charset utfEncoding = Charset.forName("UTF-8"); sb.append(" : ").append(new String(holder.data, utfEncoding).trim()); } ((TextView) convertView).setText(sb.toString()); } return convertView; } }; listMemBlock.setAdapter(adapter); // ????? //listMemBlock.setItemsCanFocus(false); //? listMemBlock.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listMemBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //????? SparseBooleanArray arry = listMemBlock.getCheckedItemPositions(); ByteBuffer buff = ByteBuffer.allocate(arry.size() * memInfo.getBlockSize()); int writableBlockCount = 0; for (int i = 0; i < arry.size(); i++) { int key = arry.keyAt(i); //????? Object o = parent.getItemAtPosition(key); if (o != null && o instanceof ViewHolder) { ViewHolder holder = (ViewHolder) o; if (holder.isWritable) { writableBlockCount++; if (holder.data != null && holder.data.length > 0) { buff.put(holder.data); } } } } //UTF-8? StringBuilder sb = new StringBuilder(); Charset utfEncoding = Charset.forName("UTF-8"); sb.append(new String(buff.array(), utfEncoding).trim()); editWrite.setHint(memInfo.getBlockSize() * writableBlockCount + "??"); if (writableBlockCount > 0) { editWrite.setText(sb.toString().trim()); editWrite.setTag(arry); //???????????? btnWrite.setEnabled(true); editWrite.setEnabled(true); } else { btnWrite.setEnabled(false); editWrite.setEnabled(false); } } }); } catch (ISO15693Exception e) { e.printStackTrace(); Log.e(TAG, e.toString()); } }