Example usage for android.view ActionMode getMenuInflater

List of usage examples for android.view ActionMode getMenuInflater

Introduction

In this page you can find the example usage for android.view ActionMode getMenuInflater.

Prototype

public abstract MenuInflater getMenuInflater();

Source Link

Document

Returns a MenuInflater with the ActionMode's context.

Usage

From source file:com.makotojava.android.debate.PolicySpeechFragment.java

private void createCrossExTimerOnLongClickListener(TextView speechTimer) {
    speechTimer.setOnLongClickListener(new OnLongClickListener() {
        @Override//from  w  w w . j  a v  a 2  s.  com
        public boolean onLongClick(View v) {
            getActivity().startActionMode(new ActionMode.Callback() {
                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {
                    // Nothing to do
                }

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

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    boolean ret = false;
                    switch (item.getItemId()) {
                    case R.id.crossex_context_menu_reset:
                        Log.i(TAG, "CONTEXT MENU: CrossEx Timer **RESET**");
                        long originalDurationInMillis = _crossexTimer.reset();
                        updateTimerTextView(_crossexTimerTextView, originalDurationInMillis);
                        _crossexTimerTextView.setTextColor(Color.BLACK);
                        mode.finish();
                        ret = true;
                        break;
                    case R.id.crossex_context_menu_set:
                        Log.i(TAG, "CONTEXT MENU: CrossEx Timer **SET**");
                        // Display dialog to set Timer
                        FragmentManager fragMan = getActivity().getFragmentManager();
                        TimePickerFragment dialog = TimePickerFragment.newInstance(
                                _crossexTimer.getMillisUntilFinished(), _speech.getCrossExDurationInMinutes(),
                                RQID_CROSSEXTIMER);
                        dialog.setTargetFragment(PolicySpeechFragment.this, 0);
                        dialog.show(fragMan, MINUTES_SECONDS_PICKER_TITLE);
                        _crossexTimerTextView.setTextColor(Color.BLACK);
                        mode.finish();
                        ret = true;
                        break;
                    }
                    return ret;
                }
            });
            return true;
        }
    });
}

From source file:com.notepadlite.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else/*w ww  .  j av a 2 s .  c  om*/
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    final ArrayList<String> cab = new ArrayList<>(numOfNotes);

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

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
            case R.id.action_export:
                mode.finish(); // Action picked, so close the CAB
                listener.exportNote(cab.toArray());
                return true;
            case R.id.action_delete:
                mode.finish(); // Action picked, so close the CAB
                listener.deleteNote(cab.toArray());
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            listener.hideFab();

            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);

            // Clear any old values from cab array
            cab.clear();

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            listener.showFab();
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Add/remove filenames to cab array as they are checked/unchecked
            if (checked) {
                if (sortBy.equals("date"))
                    cab.add(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.add(finalListByName[position]);
            } else {
                if (sortBy.equals("date"))
                    cab.remove(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.remove(finalListByName[position]);
            }

            // Update the title in CAB
            if (cab.size() == 0)
                mode.setTitle("");
            else
                mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
        }

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

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:fr.simon.marquis.secretcodes.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    getSupportActionBar().setTitle(Utils.applyCustomTypeFace(getString(R.string.app_name), this));
    setContentView(R.layout.activity_main);
    mEmptyView = findViewById(R.id.emptyView);
    mGridView = (GridView) findViewById(R.id.gridView);
    mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
    mGridView.setAdapter(new SecretCodeAdapter(this, Utils.getSecretCodes(this)));
    mGridView.setEmptyView(mEmptyView);/* ww  w  . j a  v  a  2  s .c om*/
    mEmptyView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mEmptyView.setEnabled(false);
            mEmptyView.animate().alpha(0)
                    .setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));
            startService(new Intent(MainActivity.this, CrawlerService.class));
        }
    });
    mGridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String code = ((SecretCode) arg0.getItemAtPosition(arg2)).getCode();
            Toast.makeText(MainActivity.this, getString(R.string.execute_code, code), Toast.LENGTH_SHORT)
                    .show();
            try {
                sendBroadcast(new Intent("android.provider.Telephony.SECRET_CODE",
                        Uri.parse("android_secret_code://" + code)));
            } catch (java.lang.SecurityException se) {
                Toast.makeText(MainActivity.this, R.string.security_exception, Toast.LENGTH_LONG).show();
            }
        }
    });

    mGridView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            ((SecretCodeAdapter) mGridView.getAdapter()).itemCheckedStateChanged(position, checked);
            mode.setTitle(Html.fromHtml("<b>" + mGridView.getCheckedItemCount() + "</b>"));
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_delete:
                ((SecretCodeAdapter) mGridView.getAdapter()).deleteSelection(getApplicationContext());
                mode.finish();
                return true;
            case R.id.action_select_all:
                boolean check = mGridView.getCheckedItemCount() != mGridView.getCount();
                for (int i = 0; i < mGridView.getCount(); i++) {
                    mGridView.setItemChecked(i, check);
                }
                return true;
            default:
                return false;
            }
        }

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

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            ((SecretCodeAdapter) mGridView.getAdapter()).resetSelection();
            supportInvalidateOptionsMenu();
        }

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

    });

    supportInvalidateOptionsMenu();
}

From source file:com.anjalimacwan.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else/*w w w. java 2s  . c  o m*/
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final ArrayList<String> cab = new ArrayList<>(numOfNotes);

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

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB
                switch (item.getItemId()) {
                case R.id.action_export:
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNote(cab.toArray());
                    return true;
                case R.id.action_delete:
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNote(cab.toArray());
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                listener.hideFab();

                // Inflate the menu for the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);

                // Clear any old values from cab array
                cab.clear();

                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                listener.showFab();
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.equals("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.equals("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.remove(finalListByName[position]);
                }

                // Update the title in CAB
                if (cab.size() == 0)
                    mode.setTitle("");
                else
                    mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
            }

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

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:fr.simon.marquis.preferencesmanager.ui.PreferencesFragment.java

void updateListView(PreferenceFile p, boolean animate) {
    if (getActivity() == null || getActivity().isFinishing()) {
        return;//from ww w  .  ja  v  a 2 s  .c om
    }
    if (p == null) {
        getActivity().finish();
        return;
    }
    preferenceFile = p;
    emptyViewText.setText(preferenceFile.isValidPreferenceFile() ? R.string.empty_preference_file_valid
            : R.string.empty_preference_file_invalid);
    loadingView.setVisibility(View.GONE);
    gridView.setVisibility(View.VISIBLE);

    if (animate) {
        if (getActivity() != null) {
            Animation fadeOut = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
            if (fadeOut != null) {
                loadingView.startAnimation(fadeOut);
            }
            Animation fadeIn = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in);
            if (fadeIn != null) {
                gridView.startAnimation(fadeIn);
            }
        }
    }

    gridView.setAdapter(new PreferenceAdapter(getActivity(), this));
    gridView.setEmptyView(emptyView);
    gridView.setOnItemClickListener(new OnItemClickListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            Entry<String, Object> item = (Entry<String, Object>) gridView.getAdapter().getItem(arg2);
            PreferenceType type = PreferenceType.fromObject(item.getValue());
            if (type == PreferenceType.UNSUPPORTED) {
                Toast.makeText(getActivity(), R.string.preference_unsupported, Toast.LENGTH_SHORT).show();
            } else {
                showPrefDialog(type, true, item.getKey(), item.getValue());
            }
        }
    });
    gridView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            ((PreferenceAdapter) gridView.getAdapter()).itemCheckedStateChanged(position, checked);
            mode.setTitle(Html.fromHtml("<b>" + gridView.getCheckedItemCount() + "</b>"));
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_delete:
                ((PreferenceAdapter) gridView.getAdapter()).deleteSelection();
                Utils.savePreferences(preferenceFile, mFile, mPackageName, getActivity());
                ((PreferenceAdapter) gridView.getAdapter()).notifyDataSetChanged();
                mode.finish();
                return true;
            case R.id.action_select_all:
                boolean check = gridView.getCheckedItemCount() != gridView.getCount();
                for (int i = 0; i < gridView.getCount(); i++) {
                    gridView.setItemChecked(i, check);
                }
                return true;
            default:
                return false;
            }
        }

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

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            ((PreferenceAdapter) gridView.getAdapter()).resetSelection();
            getActivity().invalidateOptionsMenu();
        }

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

    });
    getActivity().invalidateOptionsMenu();
}

From source file:org.readium.sdk.android.biblemesh.WebViewActivity.java

@Override
public void onActionModeStarted(ActionMode mode) {
    if (mActionMode == null) {
        mActionMode = mode;/*from w w  w  .  jav a2 s. co  m*/
        Menu menu = mode.getMenu();
        // Remove the default menu items (select all, copy, paste, search)
        menu.clear();

        // If you want to keep any of the defaults,
        // remove the items you don't want individually:
        // menu.removeItem(android.R.id.[id_of_item_to_remove])

        // Inflate your own menu items
        mode.getMenuInflater().inflate(R.menu.context_menu, menu);

        MenuItem item = menu.findItem(R.id.highlight_item);
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                mReadiumJSApi.highlightSelection();
                return true;
            }
        });
    }

    super.onActionModeStarted(mode);
}

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

@SuppressLint({ "InlinedApi", "NewApi" })
@Override//from   w  ww.  ja  v  a  2s  .com
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: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);
        }/*from  w ww  .  j  a  v  a  2  s  .co  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:org.spinsuite.bchat.view.FV_ThreadIndex.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
        @Override//from   w  w w  .j av  a 2  s  .c  om
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Capture total checked items
            final int checkedCount = getListView().getCheckedItemCount();
            // Set the CAB title according to total checked items
            mode.setTitle(checkedCount + " " + getString(R.string.BChat_Selected));
            // Calls toggleSelection method from ListViewAdapter Class
            m_Adapter.toggleSelection(position);

        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_delete:
                SparseBooleanArray selectedItems = m_Adapter.getSelectedItems();
                String[] ids = new String[selectedItems.size()];
                for (int i = (selectedItems.size() - 1); i >= 0; i--) {
                    if (selectedItems.valueAt(i)) {
                        DisplayBChatThreadListItem selectedItem = m_Adapter.getItem(selectedItems.keyAt(i));
                        //   Add Value
                        ids[i] = selectedItem.getSPS_BC_Request_UUID();
                        //   Remove Item
                        m_Adapter.remove(selectedItem);
                    }
                }
                //   Delete Records in DB
                if (ids.length > 0) {
                    BCMessageHandle.getInstance(m_ctx).deleteRequest(ids);
                }
                mode.finish();
                return true;
            default:
                return false;
            }
        }

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

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            m_Adapter.removeSelection();
        }

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

    });
}

From source file:de.azapps.mirakel.main_activity.tasks_fragment.TasksFragment.java

@SuppressLint("NewApi")
protected void update(final boolean reset) {
    if (!this.created) {
        return;// w w  w  .  ja  v a  2  s . co m
    }
    this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
    this.adapter = new TaskAdapter(getActivity(), new OnTaskChangedListner() {
        @Override
        public void onTaskChanged(final Task newTask) {
            getLoaderManager().restartLoader(0, null, TasksFragment.this);
            if (MirakelCommonPreferences.isTablet() && TasksFragment.this.main.getTaskFragment() != null
                    && TasksFragment.this.main.getTaskFragment().getTask().getId() == newTask.getId()) {
                TasksFragment.this.main.getTaskFragment().update(newTask);
            }
        }
    });
    adapter.setFilterQueryProvider(this);
    this.listView.setAdapter(this.adapter);
    getLoaderManager().initLoader(0, null, this);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        this.listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, final View item, final int position,
                    final long id) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                final Task task = Task.get((Long) item.getTag()).orNull();
                if (task == null) {
                    return false;
                }
                builder.setTitle(task.getName());
                final List<CharSequence> items = new ArrayList<CharSequence>(
                        Arrays.asList(getActivity().getResources().getStringArray(R.array.task_actions_items)));
                builder.setItems(items.toArray(new CharSequence[items.size()]),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int item) {
                                switch (item) {
                                case TASK_RENAME:
                                    TasksFragment.this.main.setCurrentTask(task);
                                    break;
                                case TASK_MOVE:
                                    TasksFragment.this.main.handleMoveTask(task);
                                    break;
                                case TASK_DESTROY:
                                    TasksFragment.this.main.handleDestroyTask(task);
                                    break;
                                default:
                                    break;
                                }
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        });
    } else {
        this.listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
        this.listView.setHapticFeedbackEnabled(true);
        this.listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
            @Override
            public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
                switch (item.getItemId()) {
                case R.id.menu_delete:
                    TasksFragment.this.main.handleDestroyTask(TasksFragment.this.selectedTasks);
                    break;
                case R.id.menu_move:
                    TasksFragment.this.main.handleMoveTask(TasksFragment.this.selectedTasks);
                    break;
                case R.id.menu_set_due:
                    TasksFragment.this.main.handleSetDue(TasksFragment.this.selectedTasks);
                    break;
                case R.id.edit_task:
                    TasksFragment.this.main.setCurrentTask(TasksFragment.this.selectedTasks.get(0), true);
                    break;
                case R.id.done_task:
                    for (final Task t : TasksFragment.this.selectedTasks) {
                        t.setDone(true);
                        t.save();
                    }
                    getLoaderManager().restartLoader(0, null, TasksFragment.this);
                    break;
                default:
                    break;
                }
                mode.finish();
                return false;
            }

            @Override
            public boolean onCreateActionMode(final ActionMode mode, final Menu menu) {
                final MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_tasks, menu);
                TasksFragment.this.mActionMode = mode;
                clearFocus();
                TasksFragment.this.selectedTasks = new ArrayList<>();
                return true;
            }

            @Override
            public void onDestroyActionMode(final ActionMode mode) {
                TasksFragment.this.selectedTasks = new ArrayList<>();
            }

            @Override
            public void onItemCheckedStateChanged(final ActionMode mode, final int position, final long id,
                    final boolean checked) {
                final Cursor cursor = (Cursor) TasksFragment.this.listView.getItemAtPosition(position);
                if (cursor.getCount() > 0) {
                    final Task t = new Task(cursor);
                    if (!TasksFragment.this.selectedTasks.contains(t) && checked) {
                        TasksFragment.this.selectedTasks.add(t);
                    } else if (checked) {
                        TasksFragment.this.selectedTasks.remove(t);
                    }
                }
            }

            @Override
            public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
                menu.findItem(R.id.edit_task).setVisible(TasksFragment.this.selectedTasks.size() <= 1);
                return false;
            }
        });
    }
    this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View item, final int position,
                final long id) {
            long taskId = (Long) item.getTag();
            Optional<Task> taskOptional = Task.get(taskId);
            if (taskOptional.isPresent()) {
                TasksFragment.this.main.setCurrentTask(taskOptional.get(), true);
            } else {
                throw new TaskVanishedException(taskId);
            }
        }
    });
}