Example usage for android.util SparseBooleanArray keyAt

List of usage examples for android.util SparseBooleanArray keyAt

Introduction

In this page you can find the example usage for android.util SparseBooleanArray keyAt.

Prototype

public int keyAt(int index) 

Source Link

Document

Given an index in the range 0...size()-1, returns the key from the indexth key-value mapping that this SparseBooleanArray stores.

Usage

From source file:com.btmura.android.reddit.app.NavigationFragment.java

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    int count = getListView().getCheckedItemCount();
    boolean aboutItemVisible = count == 1;
    boolean shareItemsVisible = count == 1;
    boolean deleteItemVisible = true;

    SparseBooleanArray checked = getListView().getCheckedItemPositions();
    int size = checked.size();
    for (int i = 0; i < size; i++) {
        if (checked.valueAt(i)) {
            int position = checked.keyAt(i);
            int adapterIndex = mergeAdapter.getAdapterIndex(position);
            switch (adapterIndex) {
            case ADAPTER_ACCOUNTS:
            case ADAPTER_PLACES:
                aboutItemVisible = shareItemsVisible = deleteItemVisible = false;
                break;

            case ADAPTER_SUBREDDITS:
                int adapterPosition = mergeAdapter.getAdapterPosition(position);
                String subreddit = subredditAdapter.getName(adapterPosition);
                boolean hasSidebar = Subreddits.hasSidebar(subreddit);
                aboutItemVisible &= hasSidebar;
                shareItemsVisible &= hasSidebar;
                deleteItemVisible &= hasSidebar;
                break;
            }/*from  w w  w.j  a  v  a 2 s .c om*/
        }
    }

    if (aboutItemVisible || shareItemsVisible || deleteItemVisible) {
        prepareMode(mode, count);
        prepareAddItem(menu);
        prepareAboutItem(menu, aboutItemVisible);
        prepareDeleteItem(menu, deleteItemVisible);
        prepareShareItems(menu, shareItemsVisible);
    } else {
        mode.finish();
    }

    return true;
}

From source file:de.qspool.clementineremote.ui.fragments.PlaylistFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_playlist, container, false);

    mPlaylists = mPlaylistManager.getAllPlaylists();

    mList = (ListView) view.findViewById(R.id.songs);
    mEmptyPlaylist = view.findViewById(R.id.playlist_empty);

    // Add Spinner to toolbar
    mPlaylistsSpinner = (Spinner) getActivity().findViewById(R.id.toolbar_spinner);

    mPlaylistsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override/*from  w w  w . j  av a 2 s  .  c  o  m*/
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            updateSongList();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    updatePlaylistSpinner();

    // Create the adapter
    mAdapter = new PlaylistSongAdapter(getActivity(), R.layout.item_playlist, getSelectedPlaylistSongs());

    mList.setOnItemClickListener(oiclSong);
    mList.setAdapter(mAdapter);

    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
            SparseBooleanArray checkedPositions = mList.getCheckedItemPositions();
            LinkedList<MySong> selectedSongs = new LinkedList<>();

            for (int i = 0; i < checkedPositions.size(); ++i) {
                int position = checkedPositions.keyAt(i);
                if (checkedPositions.valueAt(i)) {
                    selectedSongs.add(getSelectedPlaylistSongs().get(position));
                }
            }

            if (!selectedSongs.isEmpty()) {
                switch (item.getItemId()) {
                case R.id.playlist_context_play:
                    playSong(selectedSongs.get(0));

                    mode.finish();
                    return true;
                case R.id.playlist_context_download:
                    LinkedList<String> urls = new LinkedList<>();
                    for (MySong s : selectedSongs) {
                        urls.add(s.getUrl());
                    }
                    if (!urls.isEmpty()) {
                        DownloadManager.getInstance().addJob(
                                ClementineMessageFactory.buildDownloadSongsMessage(DownloadItem.Urls, urls));
                    }
                    mode.finish();
                    return true;
                case R.id.playlist_context_remove:
                    Message msg = Message.obtain();
                    msg.obj = ClementineMessageFactory.buildRemoveMultipleSongsFromPlaylist(getPlaylistId(),
                            selectedSongs);
                    App.ClementineConnection.mHandler.sendMessage(msg);
                    mode.finish();
                    return true;
                default:
                    return false;
                }
            }
            return false;
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) {
            android.view.MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.playlist_context_menu, menu);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.grey_cab_status));

            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, android.view.Menu menu) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.actionbar_dark));
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        }
    });

    // Filter the results
    mAdapter.getFilter().filter(mFilterText);

    mActionBar.setTitle("");
    mActionBar.setSubtitle("");

    return view;
}

From source file:org.tigase.mobile.bookmarks.BookmarksActivity.java

@TargetApi(11)
private void initializeContextActions() {

    listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        private Bookmark getBookmarkFromFlatPosition(int pos) {
            long packed = listView.getExpandableListPosition(pos);
            int child = ExpandableListView.getPackedPositionChild(packed);
            int group = ExpandableListView.getPackedPositionGroup(packed);

            return (Bookmark) adapter.getChild(group, child);
        }//ww w .  j av  a 2  s.  c o m

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            SparseBooleanArray selection = listView.getCheckedItemPositions();

            if (item.getItemId() == R.id.edit) {
                for (int i = 0; i < selection.size(); i++) {
                    if (selection.valueAt(i)) {
                        int pos = selection.keyAt(i);

                        Bookmark bookmark = getBookmarkFromFlatPosition(pos);
                        editItem(bookmark);
                    }
                }
                mode.finish(); // Action picked, so close the CAB
                return true;
            } else if (item.getItemId() == R.id.remove) {
                List<Bookmark> items = new ArrayList<Bookmark>();
                for (int i = 0; i < selection.size(); i++) {
                    if (selection.valueAt(i)) {
                        int pos = selection.keyAt(i);

                        Bookmark bookmark = getBookmarkFromFlatPosition(pos);
                        if (bookmark != null) {
                            items.add(bookmark);
                        }
                    }
                }
                removeItems(items);
                mode.finish();
                return true;
            } else {
                return false;
            }

        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.bookmarks_context_menu, menu);
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            Menu menu = mode.getMenu();
            for (int i = 0; i < menu.size(); i++) {
                MenuItem mi = menu.getItem(i);
                if (mi.getItemId() == R.id.edit) {
                    mi.setVisible(listView.getCheckedItemCount() < 2);
                }
            }
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return true;
        }

    });
}

From source file:com.github.jvanhie.discogsscrobbler.NowPlayingFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setSelection(final ListView list) {
    list.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    list.setSelector(R.drawable.track_selector);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override/* w w  w.j a  va  2  s  .c  o m*/
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (mBound) {
                //fully stop previous playlist since we start again from the beginning of the selected track
                ArrayList<Track> trackList = new ArrayList<Track>(mService.trackList);
                mService.stop();
                mService.trackList = trackList;
                mService.currentTrack = i;
                mService.resume();
            }
        }
    });
    list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {

        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater inflater = getActivity().getMenuInflater();
            inflater.inflate(R.menu.now_playing_cab, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            SparseBooleanArray checkedItems = list.getCheckedItemPositions();
            final List<Integer> positions = new ArrayList<Integer>();
            if (checkedItems != null) {
                for (int i = 0; i < checkedItems.size(); i++) {
                    if (checkedItems.valueAt(i)) {
                        positions.add(checkedItems.keyAt(i));
                    }
                }
            }
            switch (menuItem.getItemId()) {
            case R.id.play_selection:
                if (mBound) {
                    //change tracklist and start over again
                    ArrayList<Track> newTrackList = new ArrayList<Track>();
                    for (Integer i : positions) {
                        newTrackList.add(mService.trackList.get(i));
                    }
                    //fully stop previous playlist since we start again from the beginning
                    mService.stop();
                    mService.trackList = newTrackList;
                    mService.currentTrack = 0;
                    mService.resume();
                }
                actionMode.finish();
                break;
            case R.id.remove_selection:
                int currPlaying = mService.currentTrack;
                int newPlaying = -1;
                //change tracklist and start over again
                ArrayList<Track> newTrackList = new ArrayList<Track>();
                for (int i = 0; i < mService.trackList.size(); i++) {
                    if (!positions.contains(i)) {
                        newTrackList.add(mService.trackList.get(i));
                    }
                    //calculate new currently playing counter
                    if (i == currPlaying) {
                        if (positions.contains(i)) {
                            currPlaying++;
                        } else {
                            newPlaying = newTrackList.size() - 1;
                        }
                    }
                }
                //the currently playing track was removed, start fresh from the next available
                if (currPlaying != mService.currentTrack) {
                    mService.stop();
                    if (newPlaying != -1) {
                        mService.trackList = newTrackList;
                        mService.currentTrack = newPlaying;
                        mService.resume();
                    }
                } else {
                    //pause the playlist and resume with the new tracklist
                    mService.pause();
                    mService.trackList = newTrackList;
                    mService.currentTrack = newPlaying;
                    mService.resume();
                }
                actionMode.finish();
                break;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });
}

From source file:com.btmura.android.reddit.app.NavigationFragment.java

private String[] getCheckedSubreddits() {
    ListView lv = getListView();/*from   w  w w . ja  v a  2 s.  c o m*/
    SparseBooleanArray checked = lv.getCheckedItemPositions();
    String[] subreddits = new String[lv.getCheckedItemCount()];

    int size = checked.size();
    int j = 0;
    for (int i = 0; i < size; i++) {
        if (checked.valueAt(i)) {
            int position = checked.keyAt(i);
            int adapterPosition = mergeAdapter.getAdapterPosition(position);
            subreddits[j++] = subredditAdapter.getName(adapterPosition);
        }
    }

    return subreddits;
}

From source file:org.akop.crosswords.fragment.SubscriptionDetailFragment.java

private void saveCheckedItems() {
    int checkedCount = mListView.getCheckedItemCount();
    if (checkedCount > 0) {
        // Make a list of checked items
        PuzzleWrapper[] checkedItems = new PuzzleWrapper[checkedCount];
        SparseBooleanArray checked = mListView.getCheckedItemPositions();
        for (int i = 0, n = checked.size(), j = 0; i < n; i++) {
            if (checked.valueAt(i)) {
                checkedItems[j++] = mAdapter.getItem(checked.keyAt(i));
            }//w w w . ja  v  a  2 s.  c o m
        }

        // Kick off the writer task
        WriterTask task = new WriterTask(false);
        task.execute(checkedItems);
    }
}

From source file:com.github.jvanhie.discogsscrobbler.ReleaseListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setSelection() {
    mList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setSelector(R.drawable.track_selector);
    mList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        @Override/*from  w  ww .  j a v a  2s .c  om*/
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = getActivity().getMenuInflater();
            inflater.inflate(R.menu.list_cab, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
            SparseBooleanArray checkedItems = mList.getCheckedItemPositions();
            final List<Release> releases = new ArrayList<Release>();
            if (checkedItems != null) {
                for (int i = 0; i < checkedItems.size(); i++) {
                    if (checkedItems.valueAt(i)) {
                        releases.add((Release) mList.getAdapter().getItem(checkedItems.keyAt(i)));
                    }
                }
            }
            switch (item.getItemId()) {
            case R.id.reload_release:
                mCallbacks.setRefreshVisible(true);
                mDiscogs.refreshReleases(releases, new Discogs.DiscogsWaiter() {
                    @Override
                    public void onResult(boolean success) {
                        if (success) {
                            Toast.makeText(getActivity(), "reloaded releases", Toast.LENGTH_SHORT).show();
                            loadList();
                        } else {
                            Toast.makeText(getActivity(), "Failed to reload requested releases!",
                                    Toast.LENGTH_SHORT).show();
                        }
                        mCallbacks.setRefreshVisible(false);
                    }
                });
                mode.finish();
                break;
            case R.id.delete_release:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                // Add the buttons
                builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked OK button
                        mCallbacks.setRefreshVisible(true);
                        mDiscogs.removeReleases(releases, new Discogs.DiscogsWaiter() {
                            @Override
                            public void onResult(boolean success) {
                                if (success) {
                                    Toast.makeText(getActivity(), "Removed selected releases",
                                            Toast.LENGTH_SHORT).show();
                                    loadList();
                                } else {
                                    Toast.makeText(getActivity(), "Failed to remove selected releases!",
                                            Toast.LENGTH_SHORT).show();
                                }
                                mCallbacks.setRefreshVisible(false);
                            }
                        });
                        mode.finish();
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mode.finish();
                    }
                });
                builder.setTitle(R.string.delete_releases_title).setMessage(R.string.delete_releases_message);
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case R.id.cancel_selection:
                mode.finish();
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            mode.setTitle(mList.getCheckedItemCount() + " releases selected");

        }

    });
}

From source file:com.concentricsky.android.khanacademy.app.ManageDownloadsActivity.java

private void confirmAndDelete() {
    View contentView = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null, false);
    ListView list = (ListView) contentView.findViewById(R.id.dialog_confirm_delete_list);

    ArrayList<String> titles = new ArrayList<String>();
    final HashSet<Video> videos = new HashSet<Video>();

    SparseBooleanArray positions = gridView.getCheckedItemPositions();
    int n = positions.size();
    for (int i = 0; i < n; ++i) {
        Cursor c = (Cursor) gridView.getItemAtPosition(positions.keyAt(i));
        Video v = new Video();
        v.setReadable_id(c.getString(c.getColumnIndex("readable_id")));
        v.setYoutube_id(c.getString(c.getColumnIndex("youtube_id")));
        v.setDlm_id(c.getLong(c.getColumnIndex("dlm_id")));
        videos.add(v);/*from  ww  w. ja v  a2  s  . com*/
        titles.add(c.getString(c.getColumnIndex("title")));
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.dialog_confirm_delete_item);
    adapter.addAll(titles);
    list.setAdapter(adapter);

    new AlertDialog.Builder(this).setView(contentView).setMessage(getString(R.string.msg_delete_videos))
            .setPositiveButton(getString(R.string.button_confirm_delete),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            deleteItems(videos);
                            if (actionMode != null) {
                                actionMode.finish();
                            }
                        }
                    })
            .setNegativeButton(getString(R.string.button_cancel), null).show();
}

From source file:org.totschnig.myexpenses.fragment.MethodList.java

@Override
public boolean dispatchCommandMultiple(int command, SparseBooleanArray positions, Long[] itemIds) {
    switch (command) {
    case R.id.DELETE_COMMAND:
        int columnIndexMappedTransactions = mMethodsCursor
                .getColumnIndex(DatabaseConstants.KEY_MAPPED_TRANSACTIONS);
        int columnIndexMappedTemplates = mMethodsCursor.getColumnIndex(DatabaseConstants.KEY_MAPPED_TEMPLATES);
        int columnIndexRowId = mMethodsCursor.getColumnIndex(DatabaseConstants.KEY_ROWID);
        int mappedTransactionsCount = 0, mappedTemplatesCount = 0;
        ArrayList<Long> idList = new ArrayList<>();
        for (int i = 0; i < positions.size(); i++) {
            if (positions.valueAt(i)) {
                boolean deletable = true;
                mMethodsCursor.moveToPosition(positions.keyAt(i));
                if (mMethodsCursor.getInt(columnIndexMappedTransactions) > 0) {
                    mappedTransactionsCount++;
                    deletable = false;/*from  w  ww  .  ja  va  2  s  .co  m*/
                }
                if (mMethodsCursor.getInt(columnIndexMappedTemplates) > 0) {
                    mappedTemplatesCount++;
                    deletable = false;
                }
                if (deletable) {
                    idList.add(mMethodsCursor.getLong(columnIndexRowId));
                }
            }
        }
        if (!idList.isEmpty()) {
            ((ProtectedFragmentActivity) getActivity()).startTaskExecution(
                    TaskExecutionFragment.TASK_DELETE_PAYMENT_METHODS, idList.toArray(new Long[idList.size()]),
                    null, R.string.progress_dialog_deleting);
            return true;
        }
        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();
        }
        break;
    }
    return super.dispatchCommandMultiple(command, positions, itemIds);
}

From source file:com.serenegiant.aceparrot.MediaFragment.java

/**
 * ???/*from   w  w  w.  j a v  a  2 s  .co  m*/
 * @return
 */
private ARMediaObject[] getSelectedMedias() {
    ARMediaObject[] result = null;
    if (mMediaListView != null) {
        final SparseBooleanArray ids = mMediaListView.getCheckedItemPositions();
        final int n = ids != null ? ids.size() : 0;
        if (n > 0) {
            final List<ARMediaObject> list = new ArrayList<ARMediaObject>();
            for (int i = 0; i < n; i++) {
                if (ids.valueAt(i)) {
                    final Object obj = mMediaListView.getItemAtPosition(ids.keyAt(i));
                    if (obj instanceof ARMediaObject) {
                        list.add((ARMediaObject) obj);
                    }
                }
            }
            final int m = list.size();
            if (m > 0) {
                result = new ARMediaObject[m];
                list.toArray(result);
            }
        }
    }
    return result;
}