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:org.ymegane.android.approom.AppDisplayFragment.java

private void updateMultipleChoiceState(int position) {
    adapter.toggleCheckState(position);/*w  ww.  ja v  a 2  s . c  om*/
    adapter.notifyDataSetChanged();
    if (adapter.getCheckedStates().size() <= 0) {
        actionMode.finish();
        return;
    }
    SparseBooleanArray checkedItems = adapter.getCheckedStates();

    actionMode.setSubtitle(getString(R.string.action_mode_subtitle_share, checkedItems.size()));

    StringBuilder appListStr = new StringBuilder();
    for (int idx = 0; idx < checkedItems.size(); idx++) {
        int pos = checkedItems.keyAt(idx);
        AppInfo appInfo = (AppInfo) gridAppView.getItemAtPosition(pos);
        appListStr.append(appInfo.appName).append(":").append(AppLinkBase.LINK_HTTP_DETAIL)
                .append(appInfo.packageName).append("\n\n");
    }

    shareActionProvider.setShareIntent(CommonUtil.createShareIntent(appListStr.toString()));
}

From source file:com.vmihalachi.turboeditor.fragment.NavigationDrawerListFragment.java

/**
 * {@inheritDoc}//from  www .j av a  2  s .  co m
 */
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    case R.id.im_remove:
        // File paths saved in preferences
        String[] savedPaths = PreferenceHelper.getSavedPaths(getActivity());
        // We get the checked positions
        SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
        // If we have some checked positions
        if (checkedItems != null) {
            for (int i = 0; i < checkedItems.size(); i++) {
                // check if the value is checked
                if (checkedItems.valueAt(i)) {
                    // remove the checked path, but don't refresh the list
                    removePath(savedPaths[checkedItems.keyAt(i)], false);
                }
            }
            // In the end refresh the list
            refreshList();
        }
        // Close the action mode
        actionMode.finish();
        return true;
    default:
        return false;
    }
}

From source file:org.mariotaku.twidere.fragment.support.DraftsFragment.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_DELETE: {
        final DeleteDraftsConfirmDialogFragment f = new DeleteDraftsConfirmDialogFragment();
        final Bundle args = new Bundle();
        args.putLongArray(EXTRA_IDS, mListView.getCheckedItemIds());
        f.setArguments(args);/*from  ww  w.jav  a  2  s . c o m*/
        f.show(getChildFragmentManager(), "delete_drafts_confirm");
        break;
    }
    case MENU_SEND: {
        final Cursor c = mAdapter.getCursor();
        if (c == null || c.isClosed())
            return false;
        final SparseBooleanArray checked = mListView.getCheckedItemPositions();
        final List<DraftItem> list = new ArrayList<>();
        final DraftItem.CursorIndices indices = new DraftItem.CursorIndices(c);
        for (int i = 0, j = checked.size(); i < j; i++) {
            if (checked.valueAt(i) && c.moveToPosition(checked.keyAt(i))) {
                list.add(new DraftItem(c, indices));
            }
        }
        if (sendDrafts(list)) {
            final Expression where = Expression.in(new Column(Drafts._ID),
                    new RawItemArray(mListView.getCheckedItemIds()));
            mResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
        }
        break;
    }
    default: {
        return false;
    }
    }
    mode.finish();
    return true;
}

From source file:org.mariotaku.twidere.fragment.DraftsFragment.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.delete: {
        final DeleteDraftsConfirmDialogFragment f = new DeleteDraftsConfirmDialogFragment();
        final Bundle args = new Bundle();
        args.putLongArray(EXTRA_IDS, mListView.getCheckedItemIds());
        f.setArguments(args);//  w  w  w.j  a  v a2  s.  co m
        f.show(getChildFragmentManager(), "delete_drafts_confirm");
        break;
    }
    case R.id.send: {
        final Cursor c = mAdapter.getCursor();
        if (c == null || c.isClosed())
            return false;
        final SparseBooleanArray checked = mListView.getCheckedItemPositions();
        final List<Draft> list = new ArrayList<>();
        final DraftCursorIndices indices = new DraftCursorIndices(c);
        for (int i = 0, j = checked.size(); i < j; i++) {
            if (checked.valueAt(i) && c.moveToPosition(checked.keyAt(i))) {
                list.add(indices.newObject(c));
            }
        }
        if (sendDrafts(list)) {
            final Expression where = Expression.in(new Column(Drafts._ID),
                    new RawItemArray(mListView.getCheckedItemIds()));
            mResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
        }
        break;
    }
    default: {
        return false;
    }
    }
    mode.finish();
    return true;
}

From source file:au.org.ala.fielddata.mobile.ViewSavedRecordsActivity.java

private void uploadSelectedRecords() {

    boolean allDrafts = true;
    SparseBooleanArray selected = getListView().getCheckedItemPositions();
    int count = countSelected();
    int index = 0;
    int[] recordIds = new int[count];
    for (int i = 0; i < selected.size(); i++) {
        // Ignore the first item as it is help text.
        if (selected.keyAt(i) > 0) {
            if (selected.valueAt(i) == true) {
                Record record = ((RecordView) getListAdapter().getItem(selected.keyAt(i))).record;
                if (record.getStatus() != Record.Status.DRAFT) {
                    allDrafts = false;//from   ww w.j av  a2 s.c o m
                }
                recordIds[index++] = record.getId();
            }
        }
    }

    if (allDrafts) {
        showDraftsError();
    } else {
        Intent intent = new Intent(getActivity(), UploadService.class);
        intent.putExtra(UploadService.RECORD_IDS_EXTRA, recordIds);
        getActivity().startService(intent);
    }
    finishActionMode();
}

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

@SuppressLint({ "InlinedApi", "NewApi" })
@Override//w  w w .j a v  a2 s  .  c o m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_global_search, container, false);

    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.global_search_refresh_layout);
    mEmptyView = (SwipeRefreshLayout) view.findViewById(R.id.global_search_empty);

    mSwipeRefreshLayout.setColorSchemeResources(R.color.orange);
    mEmptyView.setColorSchemeResources(R.color.orange);
    mSwipeRefreshLayout.setEnabled(true);
    mEmptyView.setEnabled(true);

    mEmptyText = (TextView) view.findViewById(R.id.global_search_empty_txt);
    mList = (ListView) view.findViewById(R.id.global_search);

    mList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SongSelectItem item = mAdapters.getLast().getItem(position);

            if (item.getLevel() == mMaxLevels - 1) {
                Message msg = Message.obtain();
                LinkedList<ClementineRemoteProtocolBuffer.SongMetadata> songs = new LinkedList<>();
                songs.add(GlobalSearchManager.getInstance().getRequest().getSongFromUrl(item.getUrl()));
                msg.obj = ClementineMessageFactory
                        .buildInsertSongs(App.Clementine.getPlaylistManager().getActivePlaylistId(), songs);
                App.ClementineConnection.mHandler.sendMessage(msg);

                String text = getActivity().getResources().getQuantityString(R.plurals.songs_added, 1, 1);
                Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
            } else {
                GlobalSearchQuery globalSearchQuery = new GlobalSearchQuery(getActivity(), mQueryId);
                globalSearchQuery.openDatabase();
                globalSearchQuery.setLevel(mAdapters.size());
                globalSearchQuery.setSelection(item.getSelection());
                mAdapters.add(new DynamicSongQueryAdapter(getActivity(), globalSearchQuery));
                showList();
            }
        }
    });
    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setMultiChoiceModeListener(new MultiChoiceModeListener() {
        @Override
        public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
            SparseBooleanArray checkedPositions = mList.getCheckedItemPositions();
            final LinkedList<SongSelectItem> selectedItems = new LinkedList<>();

            for (int i = 0; i < checkedPositions.size(); ++i) {
                int position = checkedPositions.keyAt(i);
                if (checkedPositions.valueAt(i)) {
                    selectedItems.add(mAdapters.getLast().getItem(position));
                }
            }

            for (SongSelectItem songItem : selectedItems) {
                OnSongSelectFinishedListener listener;

                switch (item.getItemId()) {
                case R.id.global_search_context_add:

                    listener = new OnSongSelectFinishedListener() {
                        @Override
                        public void OnSongSelectFinished(LinkedList<SongSelectItem> l) {
                            addSongsToPlaylist(l);
                        }
                    };

                    break;
                default:
                    return false;
                }
                queryItems(songItem, listener);
            }
            mode.finish();
            return true;
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.global_search_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, 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) {
        }
    });

    GlobalSearchManager.getInstance().addOnGlobalSearchResponseListerner(this);

    setHasOptionsMenu(true);

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

    return view;
}

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

/**
 * ???// w  ww.  j  av  a2  s . c  om
 * @return
 */
private ScriptHelper.ScriptRec[] getSelectedScripts() {
    ScriptHelper.ScriptRec[] result = null;
    if (mScriptListView != null) {
        final SparseBooleanArray ids = mScriptListView.getCheckedItemPositions();
        final int n = ids != null ? ids.size() : 0;
        if (n > 0) {
            final List<ScriptHelper.ScriptRec> list = new ArrayList<ScriptHelper.ScriptRec>();
            for (int i = 0; i < n; i++) {
                if (ids.valueAt(i)) {
                    final Object obj = mScriptListView.getItemAtPosition(ids.keyAt(i));
                    if (obj instanceof ScriptHelper.ScriptRec) {
                        list.add((ScriptHelper.ScriptRec) obj);
                    }
                }
            }
            final int m = list.size();
            if (m > 0) {
                result = new ScriptHelper.ScriptRec[m];
                list.toArray(result);
            }
        }
    }
    return result;
}

From source file:org.creativecommons.thelist.activities.CategoryListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category_list);
    mContext = this;
    mMessageHelper = new MessageHelper(mContext);
    mRequestMethods = new RequestMethods(mContext);
    mSharedPref = new SharedPreferencesMethods(mContext);
    mCurrentUser = new ListUser(CategoryListActivity.this);

    //Google Analytics Tracker
    ((ListApplication) getApplication()).getTracker(ListApplication.TrackerName.GLOBAL_TRACKER);

    //Set List Adapter
    mGridView = (GridView) findViewById(R.id.categoryGrid);
    adapter = new CategoryListAdapter(this, mCategoryList);

    //Set up Helper Message if new user
    if (!mSharedPref.getCategoryHelperViewed()) {

        //UI Elements
        final View helperMessage = findViewById(R.id.category_helper_message);
        ImageButton helperCloseButton = (ImageButton) findViewById(R.id.helper_close_button);

        helperCloseButton.setOnClickListener(new View.OnClickListener() {
            @Override//from   w w  w .  j  a  va 2s.  c  o m
            public void onClick(View v) {
                helperMessage.setVisibility(View.GONE);
                mSharedPref.setCategoryHelperViewed(true);
            }
        });

        helperMessage.setVisibility(View.VISIBLE);
    }

    //Get Categories
    mRequestMethods.getCategories(new RequestMethods.ResponseCallback() {
        @Override
        public void onSuccess(JSONArray response) {
            Log.v(TAG, "> getCategories > onSuccess: " + response);
            mCategoryData = response;

            //Get users pre-selected categories
            if (!(mCurrentUser.isTempUser())) {
                //If user is logged in, request any pre-selected categories
                mRequestMethods.getUserCategories(new RequestMethods.ResponseCallback() {
                    @Override
                    public void onSuccess(JSONArray response) {
                        Log.v(TAG, "> getUserCategories > onSuccess " + response.toString());

                        //Create list of category ids
                        if (response.length() > 0) {
                            //Get array of catIds
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject singleCat = response.getJSONObject(i);
                                    mUserCategories.add(i, singleCat.getInt("categoryid"));
                                    Log.v("USERCATS", "add: " + singleCat.getInt("categoryid"));
                                } catch (JSONException e) {
                                    Log.e(TAG, e.getMessage());
                                }
                            }
                            Log.v(TAG, "users category list: " + mUserCategories.toString());
                        }
                        updateList();
                    } //onSuccess

                    @Override
                    public void onFail(VolleyError error) {
                        Log.v(TAG, "> getUserCategories > onFail " + error.toString());
                        mMessageHelper.showDialog(mContext, getString(R.string.error_title),
                                getString(R.string.error_message));
                    }
                });
            } else {

                JSONArray tempUserCategories = mSharedPref.getCategorySharedPreference();

                if (tempUserCategories != null && tempUserCategories.length() > 0) {
                    //Convert to list + add to mUserCategories
                    for (int i = 0; i < tempUserCategories.length(); i++) {
                        try {
                            mUserCategories.add(i, tempUserCategories.getInt(i));
                            Log.v(TAG, " TEMPUSER CATEGORIES: " + mUserCategories.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                updateList();
            }
        } //onSuccess

        @Override
        public void onFail(VolleyError error) {
            Log.d(TAG, "> getCategories > onFail: " + error.getMessage());
            mMessageHelper.showDialog(mContext, getString(R.string.error_title),
                    getString(R.string.error_message));
        }
    });

    //When Category is tapped
    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //ImageView checkmarkView = (ImageView)view.findViewById(R.id.checkmark);
            CheckableRelativeLayout checkableLayout = (CheckableRelativeLayout) view
                    .findViewById(R.id.checkable_layout);
            ImageView checkIcon = (ImageView) view.findViewById(R.id.category_checkmark);
            TextView categoryNameLabel = (TextView) view.findViewById(R.id.category_title);

            //Get item clicked + its category id
            CategoryListItem item = (CategoryListItem) mGridView.getItemAtPosition(position);
            String catId = String.valueOf(item.getCategoryID());

            if (mGridView.isItemChecked(position)) {
                checkableLayout.getBackground().setAlpha(128);
                checkIcon.setVisibility(View.VISIBLE);
                categoryNameLabel.setTextColor(getResources().getColor(R.color.secondary_text_material_dark));
                item.setCategoryChecked(true);
                mRequestMethods.addCategory(catId);
                //Log.v(TAG, "ADDED " + catId);
            } else {
                checkableLayout.getBackground().setAlpha(255);
                checkIcon.setVisibility(View.GONE);
                categoryNameLabel
                        .setTextColor(getResources().getColor(R.color.primary_text_default_material_dark));
                item.setCategoryChecked(false);
                mRequestMethods.removeCategory(catId);
                //Log.v(TAG, "REMOVED " + catId);
            }
            //Count how many items are checked: if at least 3, show done button
            SparseBooleanArray positions = mGridView.getCheckedItemPositions();
            int length = positions.size();
            int ItemsChecked = 0;
            if (positions.size() > 0) {
                for (int i = 0; i < length; i++) {
                    if (positions.get(positions.keyAt(i))) {
                        ItemsChecked++;
                    }
                }
            }
            if (ItemsChecked >= 1) {
                MenuItem doneButton = menu.findItem(R.id.action_done);
                doneButton.setVisible(true);
            } else {
                MenuItem doneButton = menu.findItem(R.id.action_done);
                doneButton.setVisible(false);
            }
        }
    }); //setOnItemClickListener

}

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

@Override
protected void configureMenu11(Menu menu, int count, AbsListView lv) {
    super.configureMenu11(menu, count, lv);
    switch (lv.getId()) {
    case R.id.list:
        SparseBooleanArray checkedItemPositions = mListView.getCheckedItemPositions();
        boolean hasForeignExchangeTransfer = false, hasPlan = false;
        for (int i = 0; i < checkedItemPositions.size(); i++) {
            if (checkedItemPositions.valueAt(i) && isForeignExchangeTransfer(checkedItemPositions.keyAt(i))) {
                hasForeignExchangeTransfer = true;
                break;
            }/*from  w w  w .  j ava2s  .co  m*/
        }
        for (int i = 0; i < checkedItemPositions.size(); i++) {
            if (checkedItemPositions.valueAt(i) && isPlan(checkedItemPositions.keyAt(i))) {
                hasPlan = true;
                break;
            }
        }
        configureMenuInternal(menu, count, hasForeignExchangeTransfer, hasPlan);
        break;
    case R.id.calendar_gridview:
        requirePlanMonthFragment().configureMenu11(menu, count, lv);
    }
}

From source file:com.conferenceengineer.android.iosched.ui.SessionsFragment.java

private List<Integer> getCheckedSessionPositions() {
    List<Integer> checkedSessionPositions = new ArrayList<Integer>();
    ListView listView = getListView();
    if (listView == null) {
        return checkedSessionPositions;
    }/*w  ww  . j a  v a  2  s.  c  o m*/

    SparseBooleanArray checkedPositionsBool = listView.getCheckedItemPositions();
    for (int i = 0; i < checkedPositionsBool.size(); i++) {
        if (checkedPositionsBool.valueAt(i)) {
            checkedSessionPositions.add(checkedPositionsBool.keyAt(i));
        }
    }

    return checkedSessionPositions;
}