List of usage examples for android.view ActionMode finish
public abstract void finish();
From source file:com.irateam.vkplayer.activities.ListActivity.java
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { MenuItem menuItem = navigationView.getMenu().findItem(R.id.current_playlist); switch (item.getItemId()) { case R.id.action_play: playerService.setPlaylist(audioAdapter.getCheckedItems()); playerService.play(0);/*from www .j a v a2 s . co m*/ menuItem.setChecked(true); onNavigationItemSelected(menuItem); break; case R.id.action_cache: Intent intent = new Intent(this, DownloadService.class); intent.setAction(DownloadService.START_DOWNLOADING); intent.putExtra(DownloadService.AUDIO_LIST, (ArrayList<Audio>) audioAdapter.getCheckedItems()); startService(intent); break; case R.id.action_remove_from_cache: List<Audio> list = audioAdapter.getCachedCheckedItems(); audioService.removeFromCache(list, new AudioService.Listener() { @Override public void onComplete(List<Audio> list) { audioAdapter.updateAudiosById(list); } @Override public void onError(String errorMessage) { } }); break; case R.id.action_delete: audioAdapter.removeChecked(); break; case R.id.action_add_to_playlist: List<Audio> checked = audioAdapter.getCheckedItems(); List<Audio> playlist = playerService.getPlaylist(); List<Audio> listToAdd = new ArrayList<>(); for (Audio audio : checked) { listToAdd.add(audio.clone()); } playlist.addAll(0, listToAdd); audioAdapter.notifyDataSetChanged(); Snackbar.make(coordinatorLayout, R.string.snackbar_add_to_playlist, Snackbar.LENGTH_LONG) .setAction(R.string.snackbar_cancel, (v -> { for (int i = 0; i < checked.size(); i++) playlist.remove(0); audioAdapter.notifyDataSetChanged(); })).show(); break; } mode.finish(); return true; }
From source file:pl.bcichecki.rms.client.android.fragments.EventsListFragment.java
private void performActionDelete(final ActionMode mode, MenuItem item, final Event selectedEvent) { eventsRestClient.deleteMyEvent(selectedEvent, new AsyncHttpResponseHandler() { @Override/*from ww w. ja v a 2 s . c o m*/ public void onFailure(Throwable error, String content) { Log.d(TAG, "Removing event " + selectedEvent + " failed. [error=" + error + ", content=" + content + "]"); if (error instanceof HttpResponseException) { if (((HttpResponseException) error).getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { AppUtils.showCenteredToast(getActivity(), R.string.general_unathorized_error_message_title, Toast.LENGTH_LONG); } else { AppUtils.showCenteredToast(getActivity(), R.string.general_unknown_error_message_title, Toast.LENGTH_LONG); } } else { AppUtils.showCenteredToast(getActivity(), R.string.general_unknown_error_message_title, Toast.LENGTH_LONG); } } @Override public void onFinish() { Log.d(TAG, "Attempt to delete event finished. " + selectedEvent); } @Override public void onStart() { Log.d(TAG, "Attempting to delete event. " + selectedEvent); } @Override public void onSuccess(int statusCode, String content) { Log.d(TAG, "Attempt to delete event " + selectedEvent + " succesful. Removing object locally and refreshing view..."); AppUtils.showCenteredToast(getActivity(), R.string.fragment_events_list_delete_successful, Toast.LENGTH_LONG); eventsListAdapter.remove(selectedEvent); eventsListAdapter.refresh(); mode.finish(); } }); }
From source file:org.digitalcampus.oppia.activity.DownloadMediaActivity.java
@SuppressWarnings("unchecked") @Override// w ww. ja v a2 s .c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download_media); prefs = PreferenceManager.getDefaultSharedPreferences(this); Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { missingMedia = (ArrayList<Media>) bundle.getSerializable(DownloadMediaActivity.TAG); } else { missingMedia = new ArrayList<>(); } mediaSelected = new ArrayList<>(); dmla = new DownloadMediaListAdapter(this, missingMedia); dmla.setOnClickListener(new DownloadMediaListener()); mediaList = (ListView) findViewById(R.id.missing_media_list); mediaList.setAdapter(dmla); mediaList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); mediaList.setMultiChoiceModeListener(new ListView.MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { Log.v(TAG, "Count: " + mediaList.getCheckedItemCount()); if (checked) { mediaSelected.add(missingMedia.get(position)); } else { mediaSelected.remove(missingMedia.get(position)); } int count = mediaSelected.size(); mode.setSubtitle(count == 1 ? count + " item selected" : count + " items selected"); for (Media m : mediaSelected) { if (!m.isDownloading()) { downloadSelected.setText(getString(R.string.missing_media_download_selected)); break; } } } @Override public boolean onCreateActionMode(final ActionMode mode, Menu menu) { onPrepareOptionsMenu(menu); mode.setTitle(R.string.title_download_media); if (missingMediaContainer.getVisibility() != View.VISIBLE) { missingMediaContainer.setVisibility(View.VISIBLE); downloadSelected.setOnClickListener(new OnClickListener() { public void onClick(View v) { DownloadMode downloadMode = downloadSelected.getText().equals( getString(R.string.missing_media_download_selected)) ? DownloadMode.DOWNLOAD_ALL : DownloadMode.STOP_ALL; downloadSelected.setText(downloadSelected.getText() .equals(getString(R.string.missing_media_download_selected)) ? getString(R.string.missing_media_stop_selected) : getString(R.string.missing_media_download_selected)); for (Media m : mediaSelected) { downloadMedia(m, downloadMode); } mode.finish(); } }); unselectAll.setOnClickListener(new OnClickListener() { public void onClick(View view) { mode.finish(); } }); showDownloadMediaMessage(); } dmla.setEnterOnMultiChoiceMode(true); dmla.notifyDataSetChanged(); downloadSelected.setText(getString(R.string.missing_media_stop_selected)); unselectAll.setText(getString(R.string.missing_media_unselect_all)); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_sort_by: { if (isSortByCourse) { dmla.sortByFilename(); isSortByCourse = false; item.setTitle(getString(R.string.menu_sort_by_course)); } else { dmla.sortByCourse(); isSortByCourse = true; item.setTitle(getString(R.string.menu_sort_by_filename)); } invalidateOptionsMenu(); return true; } case R.id.menu_select_all: for (int i = 0; i < mediaList.getAdapter().getCount(); i++) { if (!mediaList.isItemChecked(i)) { mediaList.setItemChecked(i, true); } } return true; default: return true; } } @Override public void onDestroyActionMode(ActionMode mode) { mediaSelected.clear(); hideDownloadMediaMessage(); dmla.setEnterOnMultiChoiceMode(false); dmla.notifyDataSetChanged(); } }); missingMediaContainer = this.findViewById(R.id.home_messages); downloadSelected = (TextView) this.findViewById(R.id.download_selected); unselectAll = (TextView) this.findViewById(R.id.unselect_all); downloadViaPCBtn = (Button) this.findViewById(R.id.download_media_via_pc_btn); downloadViaPCBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { downloadViaPC(); } }); Editor e = prefs.edit(); e.putLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, 0); e.commit(); emptyState = (TextView) findViewById(R.id.empty_state); }
From source file:org.spinsuite.bchat.view.FV_Thread.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (m_view != null) return m_view; // Inflate/*from ww w . ja v a 2 s .co m*/ m_view = inflater.inflate(R.layout.v_business_chat_thread, container, false); // Scroll lv_Thread = (ListView) m_view.findViewById(R.id.lv_Thread); et_Message = (EditText) m_view.findViewById(R.id.et_Message); ib_Send = (ImageButton) m_view.findViewById(R.id.ib_Send); // Listener ib_Send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (et_Message.getText() == null || et_Message.getText().toString().trim().length() == 0) return; // Send Message sendMessage(null); } }); // Hide Separator lv_Thread.setDividerHeight(0); lv_Thread.setDivider(null); lv_Thread.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); lv_Thread.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) { DisplayBChatThreadItem item = (DisplayBChatThreadItem) m_ThreadAdapter.getItem(position); // Show Image String fileName = item.getFileName(); if (fileName != null && fileName.length() > 0) { String m_FilePath = Env.getBC_IMG_DirectoryPathName(m_ctx); File file = new File(m_FilePath + File.separator + fileName); // Show AttachmentHandler.showAttachment(m_ctx, Uri.fromFile(file)); } } }); // lv_Thread.setMultiChoiceModeListener(new MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { // Capture total checked items final int checkedCount = lv_Thread.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_ThreadAdapter.toggleSelection(position); } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.action_delete: SparseBooleanArray selectedItems = m_ThreadAdapter.getSelectedItems(); StringBuffer inClause = new StringBuffer(); for (int i = (selectedItems.size() - 1); i >= 0; i--) { if (selectedItems.valueAt(i)) { DisplayBChatThreadItem selectedItem = m_ThreadAdapter.getItem(selectedItems.keyAt(i)); // Add Separator if (inClause.length() > 0) { inClause.append(", "); } // Add Value inClause.append("'").append(selectedItem.getSPS_BC_Message_UUID()).append("'"); // Remove Item m_ThreadAdapter.remove(selectedItem); } } // Delete Records in DB if (inClause.length() > 0) { BCMessageHandle.getInstance(m_ctx).deleteMessage(m_Request, "SPS_BC_Message_UUID IN(" + inClause.toString() + ")"); } mode.finish(); return true; case R.id.action_copy: selectedItems = m_ThreadAdapter.getSelectedItems(); boolean justOne = selectedItems.size() == 1; StringBuffer text = new StringBuffer(); for (int i = (selectedItems.size() - 1); i >= 0; i--) { if (selectedItems.valueAt(i)) { DisplayBChatThreadItem selectedItem = m_ThreadAdapter.getItem(selectedItems.keyAt(i)); // Valid File if (selectedItem.getFileName() != null) continue; // Add New Line if (text.length() > 0) { text.append(Env.NL); } // Add to Text if (justOne) { text.append(selectedItem.getText()); } else { text.append(selectedItem.getCopy()); } } } // Add To Clipboard if (text.length() > 0) { Env.setClipboardText(m_ctx, text.toString()); } mode.finish(); return true; default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.bc_thread_selected, menu); return true; } @Override public void onDestroyActionMode(ActionMode mode) { m_ThreadAdapter.removeSelection(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } }); // Return return m_view; }
From source file:com.openerp.addons.messages.Message.java
public void setupListView(List<OEListViewRows> message_list) { // Destroying pre-loaded instance and going to create new one lstview = null;/*from ww w .j a va2s . c om*/ // Fetching required messages for listview by filtering of requrement if (list != null && list.size() <= 0) { list = message_list;// getMessages(message_list); } else { rootView.findViewById(R.id.messageSyncWaiter).setVisibility(View.GONE); rootView.findViewById(R.id.txvMessageAllReadMessage).setVisibility(View.GONE); } // Handling List View controls and keys String[] from = new String[] { "subject|type", "body", "starred", "author_id|email_from", "date", "model|type" }; int[] to = new int[] { R.id.txvMessageSubject, R.id.txvMessageBody, R.id.imgMessageStarred, R.id.txvMessageFrom, R.id.txvMessageDate, R.id.txvMessageTag }; // Creating instance for listAdapter listAdapter = new OEListViewAdapter(scope.context(), R.layout.message_listview_items, list, from, to, db, true, new int[] { R.drawable.message_listview_bg_toread_selector, R.drawable.message_listview_bg_tonotread_selector }, "to_read"); // Telling adapter to clean HTML text for key value listAdapter.cleanHtmlToTextOn("body"); listAdapter.cleanDate("date", scope.User().getTimezone()); // Setting callback handler for boolean field value change. listAdapter.setBooleanEventOperation("starred", R.drawable.ic_action_starred, R.drawable.ic_action_unstarred, updateStarred); listAdapter.addViewListener(new OEListViewOnCreateListener() { @Override public View listViewOnCreateListener(int position, View row_view, OEListViewRows row_data) { String model_name = row_data.getRow_data().get("model").toString(); String model = model_name; String res_id = row_data.getRow_data().get("res_id").toString(); if (model_name.equals("false")) { model_name = capitalizeString(row_data.getRow_data().get("type").toString()); } else { String[] model_parts = TextUtils.split(model_name, "\\."); HashSet unique_parts = new HashSet(Arrays.asList(model_parts)); model_name = capitalizeString(TextUtils.join(" ", unique_parts.toArray())); } TextView msgTag = (TextView) row_view.findViewById(R.id.txvMessageTag); int tag_color = 0; if (message_model_colors.containsKey(model_name)) { tag_color = message_model_colors.get(model_name); } else { tag_color = Color.parseColor(tag_colors[tag_color_count]); message_model_colors.put(model_name, tag_color); tag_color_count++; if (tag_color_count > tag_colors.length) { tag_color_count = 0; } } if (model.equals("mail.group")) { if (UserGroups.group_names.containsKey("group_" + res_id)) { model_name = UserGroups.group_names.get("group_" + res_id); tag_color = UserGroups.menu_color.get("group_" + res_id); } } msgTag.setBackgroundColor(tag_color); msgTag.setText(model_name); TextView txvSubject = (TextView) row_view.findViewById(R.id.txvMessageSubject); TextView txvAuthor = (TextView) row_view.findViewById(R.id.txvMessageFrom); if (row_data.getRow_data().get("to_read").toString().equals("false")) { txvSubject.setTypeface(null, Typeface.NORMAL); txvSubject.setTextColor(Color.BLACK); txvAuthor.setTypeface(null, Typeface.NORMAL); txvAuthor.setTextColor(Color.BLACK); } else { txvSubject.setTypeface(null, Typeface.BOLD); txvSubject.setTextColor(Color.parseColor("#414141")); txvAuthor.setTypeface(null, Typeface.BOLD); txvAuthor.setTextColor(Color.parseColor("#414141")); } return row_view; } }); // Creating instance for listview control lstview = (ListView) rootView.findViewById(R.id.lstMessages); // Providing adapter to listview scope.context().runOnUiThread(new Runnable() { @Override public void run() { lstview.setAdapter(listAdapter); } }); // Setting listview choice mode to multiple model lstview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); // Seeting item long click listern to activate action mode. lstview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View view, int index, long arg3) { // TODO Auto-generated method stub OEListViewRows data = (OEListViewRows) lstview.getAdapter().getItem(index); Toast.makeText(scope.context(), data.getRow_id() + " id clicked", Toast.LENGTH_LONG).show(); view.setSelected(true); if (mActionMode != null) { return false; } // Start the CAB using the ActionMode.Callback defined above mActionMode = scope.context().startActionMode(mActionModeCallback); selectedCounter++; view.setBackgroundResource(R.drawable.listitem_pressed); // lstview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); return true; } }); // Setting multi choice selection listener lstview.setMultiChoiceModeListener(new MultiChoiceModeListener() { HashMap<Integer, Boolean> selectedList = new HashMap<Integer, Boolean>(); @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { // Here you can do something when items are // selected/de-selected, // such as update the title in the CAB selectedList.put(position, checked); if (checked) { selectedCounter++; } else { selectedCounter--; } if (selectedCounter != 0) { mode.setTitle(selectedCounter + ""); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // Respond to clicks on the actions in the CAB HashMap<Integer, Integer> msg_pos = new HashMap<Integer, Integer>(); OEDialog dialog = null; switch (item.getItemId()) { case R.id.menu_message_mark_unread_selected: Log.e("menu_message_context", "Mark as Unread"); for (int pos : selectedList.keySet()) { msg_pos.put(list.get(pos).getRow_id(), pos); } readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, false); readunreadoperation.execute((Void) null); mode.finish(); return true; case R.id.menu_message_mark_read_selected: Log.e("menu_message_context", "Mark as Read"); for (int pos : selectedList.keySet()) { msg_pos.put(list.get(pos).getRow_id(), pos); } readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, true); readunreadoperation.execute((Void) null); mode.finish(); return true; case R.id.menu_message_more_move_to_archive_selected: Log.e("menu_message_context", "Archive"); for (int pos : selectedList.keySet()) { msg_pos.put(list.get(pos).getRow_id(), pos); } readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, false); readunreadoperation.execute((Void) null); mode.finish(); return true; case R.id.menu_message_more_add_star_selected: for (int pos : selectedList.keySet()) { msg_pos.put(list.get(pos).getRow_id(), pos); } markasTodoTask = new PerformOperation(msg_pos, true); markasTodoTask.execute((Void) null); mode.finish(); return true; case R.id.menu_message_more_remove_star_selected: for (int pos : selectedList.keySet()) { msg_pos.put(list.get(pos).getRow_id(), pos); } markasTodoTask = new PerformOperation(msg_pos, false); markasTodoTask.execute((Void) null); mode.finish(); return true; default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // Inflate the menu for the CAB MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.menu_fragment_message_context, menu); return true; } @Override public void onDestroyActionMode(ActionMode mode) { // Here you can make any necessary updates to the activity when // the CAB is removed. By default, selected items are // deselected/unchecked. /* * Perform Operation on Selected Ids. * * row_ids are list of selected message Ids. */ selectedList.clear(); selectedCounter = 0; lstview.clearChoices(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Here you can perform updates to the CAB due to // an invalidate() request return false; } }); lstview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long id) { // TODO Auto-generated method stub MessageDetail messageDetail = new MessageDetail(); Bundle bundle = new Bundle(); bundle.putInt("message_id", list.get(index).getRow_id()); bundle.putInt("position", index); messageDetail.setArguments(bundle); scope.context().fragmentHandler.setBackStack(true, null); scope.context().fragmentHandler.replaceFragmnet(messageDetail); if (!type.equals("archive")) { list.remove(index); } listAdapter.refresh(list); } }); // Getting Pull To Refresh Attacher from Main Activity mPullToRefreshAttacher = scope.context().getPullToRefreshAttacher(); // Set the Refreshable View to be the ListView and the refresh listener // to be this. if (mPullToRefreshAttacher != null & lstview != null) { mPullToRefreshAttacher.setRefreshableView(lstview, this); } }
From source file:com.example.android.contactslist.ui.groupsEditor.GroupsEditorFragment.java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mActionModeCallback = new ActionMode.Callback() { // Called when the action mode is created; startActionMode() was called @Override/*from w ww . j ava 2 s.c o m*/ public boolean onCreateActionMode(ActionMode mode, Menu menu) { // Inflate a menu resource providing context menu items //MenuInflater inflater = mode.getMenuInflater(); //inflater.inflate(R.menu.contextual_actionbar, menu); mode.getMenuInflater().inflate(R.menu.contextual_actionbar, menu); return true; } // Called each time the action mode is shown. Always called after onCreateActionMode, but // may be called multiple times if the mode is invalidated. @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; // Return false if nothing is done } // Called when the user selects a contextual menu item @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_remove_contact: GoogleGroupMaker googleGroupMaker = new GoogleGroupMaker(getActivity()); googleGroupMaker.removeGoogleGroup(mDeleteGroupID); // method to remove group from app DB final ContactStatsContract statsDb = new ContactStatsContract(getActivity()); final GroupStatsHelper groupStatsHelper = new GroupStatsHelper(getActivity()); // delete group from the app Database final int records_updated = groupStatsHelper.removeGroupFromDB(mDeleteGroupID, statsDb); Toast.makeText(getActivity(), Long.toString(records_updated) + " Record(s) Updated", Toast.LENGTH_SHORT).show(); mode.finish(); // Action picked, so close the CAB return true; default: mode.finish(); // Action picked, so close the CAB Toast.makeText(getActivity(), "End Action Mode", Toast.LENGTH_SHORT).show(); return false; } } // Called when the user exits the action mode @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; } }; getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) { if (mActionMode != null) { return false; } // Gets the Cursor object currently bound to the ListView final Cursor cursor = mAdapter.getCursor(); // Moves to the Cursor row corresponding to the ListView item that was clicked cursor.moveToPosition(position); // Using the lookupKey because the wrong ID was being returned mDeleteGroupID = cursor.getLong(GroupsListStatsQuery.GROUP_ID); // Start the CAB using the ActionMode.Callback defined above mActionMode = getActivity().startActionMode(mActionModeCallback); view.setSelected(true); return true; } }); }
From source file:com.miz.mizuu.fragments.MovieLibraryFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.image_grid_fragment, container, false); mProgressBar = (ProgressBar) v.findViewById(R.id.progress); mEmptyLibraryLayout = v.findViewById(R.id.empty_library_layout); mEmptyLibraryTitle = (TextView) v.findViewById(R.id.empty_library_title); mEmptyLibraryTitle.setTypeface(TypefaceUtils.getRobotoCondensedRegular(mContext)); mEmptyLibraryDescription = (TextView) v.findViewById(R.id.empty_library_description); mEmptyLibraryDescription.setTypeface(TypefaceUtils.getRobotoLight(mContext)); mAdapter = new LoaderAdapter(mContext); mGridView = (ObservableGridView) v.findViewById(R.id.gridView); mGridView.setAdapter(mAdapter);//from w w w . j a v a 2 s .c o m mGridView.setColumnWidth(mImageThumbSize); mGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { viewMovieDetails(arg2, arg1); } }); // We only want to display the contextual menu if we're showing movies, not collections if (getArguments().getInt("type") != MovieLoader.COLLECTIONS) { mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL); mGridView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mAdapter.setItemChecked(position, checked); mode.setTitle(String.format(getString(R.string.selected), mAdapter.getCheckedItemCount())); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { getActivity().getMenuInflater().inflate(R.menu.movie_library_cab, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.movie_add_fav: MovieDatabaseUtils.setMoviesFavourite(mContext, mAdapter.getCheckedMovies(), true); break; case R.id.movie_remove_fav: MovieDatabaseUtils.setMoviesFavourite(mContext, mAdapter.getCheckedMovies(), false); break; case R.id.movie_watched: MovieDatabaseUtils.setMoviesWatched(mContext, mAdapter.getCheckedMovies(), true); break; case R.id.movie_unwatched: MovieDatabaseUtils.setMoviesWatched(mContext, mAdapter.getCheckedMovies(), false); break; case R.id.add_to_watchlist: MovieDatabaseUtils.setMoviesWatchlist(mContext, mAdapter.getCheckedMovies(), true); break; case R.id.remove_from_watchlist: MovieDatabaseUtils.setMoviesWatchlist(mContext, mAdapter.getCheckedMovies(), false); break; } if (!(id == R.id.watched_menu || id == R.id.watchlist_menu || id == R.id.favorite_menu)) { mode.finish(); LocalBroadcastUtils.updateMovieLibrary(mContext); } return true; } @Override public void onDestroyActionMode(ActionMode mode) { mAdapter.clearCheckedItems(); } }); } mMovieLoader = new MovieLoader(mContext, MovieLibraryType.fromInt(getArguments().getInt("type")), mCallback); mMovieLoader.load(); showProgressBar(); return v; }
From source file:de.qspool.clementineremote.ui.fragments.LibraryFragment.java
@SuppressLint({ "InlinedApi", "NewApi" }) @Override// w w w . j a v a2s. co m public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_library, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.library_refresh_layout); mEmptyLibrary = (SwipeRefreshLayout) view.findViewById(R.id.library_refresh_empty_layout); mSwipeRefreshLayout.setOnRefreshListener(this); mEmptyLibrary.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.orange); mEmptyLibrary.setColorSchemeResources(R.color.orange); mList = (ListView) view.findViewById(R.id.library); mLibraryEmptyText = (TextView) mEmptyLibrary.findViewById(R.id.library_empty_txt); mList.setOnItemClickListener(oiclLibraryClick); 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<>(); final LinkedList<String> urls = new LinkedList<>(); mLibraryQueriesDone = 0; 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 libraryItem : selectedItems) { OnSongSelectFinishedListener listener; switch (item.getItemId()) { case R.id.library_context_add: listener = new OnSongSelectFinishedListener() { @Override public void OnSongSelectFinished(LinkedList<SongSelectItem> l) { addSongsToPlaylist(l); } }; break; case R.id.library_context_download: listener = new OnSongSelectFinishedListener() { @Override public void OnSongSelectFinished(LinkedList<SongSelectItem> l) { for (SongSelectItem libItem : l) { urls.add(libItem.getUrl()); } mLibraryQueriesDone++; // Have we got all queries? if (mLibraryQueriesDone == selectedItems.size() && !urls.isEmpty()) { DownloadManager.getInstance() .addJob(ClementineMessageFactory.buildDownloadSongsMessage( ClementineRemoteProtocolBuffer.DownloadItem.Urls, urls)); } } }; break; default: return false; } queryLibraryItems(libraryItem, listener); } mode.finish(); return true; } @Override public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) { android.view.MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.library_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) { } }); createRootAdapter(); showList(); mActionBar.setTitle(""); mActionBar.setSubtitle("/"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(this); setHasOptionsMenu(true); return view; }
From source file:org.brandroid.openmanager.fragments.ContentFragment.java
public boolean createContextMenu(final OpenPath file, final AdapterView<?> list, final View view, final int pos, final int xOffset, final int yOffset) { Logger.LogInfo(getClassName() + ".onItemLongClick: " + file); final OpenContextMenuInfo info = new OpenContextMenuInfo(file); if (!OpenExplorer.USE_PRETTY_CONTEXT_MENUS) { if (Build.VERSION.SDK_INT > 10) { final PopupMenu pop = new PopupMenu(view.getContext(), view); pop.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (onOptionsItemSelected(item)) { pop.dismiss();/*from w w w. ja v a 2 s .c o m*/ return true; } else if (getExplorer() != null) return getExplorer().onIconContextItemSelected(pop, item, item.getMenuInfo(), view); return false; } }); pop.getMenuInflater().inflate(R.menu.context_file, pop.getMenu()); onPrepareOptionsMenu(pop.getMenu()); if (DEBUG) Logger.LogDebug("PopupMenu.show()"); pop.show(); return true; } else return list.showContextMenu(); } else if (OpenExplorer.BEFORE_HONEYCOMB || !OpenExplorer.USE_ACTIONMODE) { try { //View anchor = view; //view.findViewById(R.id.content_context_helper); //if(anchor == null) anchor = view; //view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //Rect r = new Rect(view.getLeft(),view.getTop(),view.getMeasuredWidth(),view.getMeasuredHeight()); MenuBuilder cmm = IconContextMenu.newMenu(list.getContext(), R.menu.context_file); if (!file.canRead()) { MenuUtils.setMenuEnabled(cmm, false); MenuUtils.setMenuEnabled(cmm, true, R.id.menu_context_info); } MenuUtils.setMenuEnabled(cmm, file.canWrite(), R.id.menu_context_paste, R.id.menu_context_cut, R.id.menu_context_delete, R.id.menu_context_rename); onPrepareOptionsMenu(cmm); //if(!file.isArchive()) hideItem(cmm, R.id.menu_context_unzip); if (getClipboard().size() > 0) MenuUtils.setMenuVisible(cmm, false, R.id.menu_multi); else MenuUtils.setMenuVisible(cmm, false, R.id.menu_context_paste); MenuUtils.setMenuEnabled(cmm, !file.isDirectory(), R.id.menu_context_edit, R.id.menu_context_view); final IconContextMenu cm = new IconContextMenu(list.getContext(), cmm, view); //cm.setAnchor(anchor); cm.setNumColumns(2); cm.setOnIconContextItemSelectedListener(getExplorer()); cm.setInfo(info); cm.setTextLayout(R.layout.context_item); cm.setTitle(file.getName()); if (!cm.show()) //r.left, r.top); return list.showContextMenu(); else return true; } catch (Exception e) { Logger.LogWarning("Couldn't show Iconified menu.", e); return list.showContextMenu(); } } if (!OpenExplorer.BEFORE_HONEYCOMB && OpenExplorer.USE_ACTIONMODE) { if (!file.isDirectory() && mActionMode == null && !getClipboard().isMultiselect()) { try { Method mStarter = getActivity().getClass().getMethod("startActionMode"); mActionMode = mStarter.invoke(getActivity(), new ActionModeHelper.Callback() { //@Override public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) { return false; } //@Override public void onDestroyActionMode(android.view.ActionMode mode) { mActionMode = null; mActionModeSelected = false; } //@Override public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.context_file, menu); mActionModeSelected = true; return true; } //@Override public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) { //ArrayList<OpenPath> files = new ArrayList<OpenPath>(); //OpenPath file = mLastPath.getChild(mode.getTitle().toString()); //files.add(file); if (item.getItemId() != R.id.menu_context_cut && item.getItemId() != R.id.menu_multi && item.getItemId() != R.id.menu_context_copy) { mode.finish(); mActionModeSelected = false; } return executeMenu(item.getItemId(), mode, file); } }); Class cAM = Class.forName("android.view.ActionMode"); Method mST = cAM.getMethod("setTitle", CharSequence.class); mST.invoke(mActionMode, file.getName()); } catch (Exception e) { Logger.LogError("Error using ActionMode", e); } } return true; } if (file.isDirectory() && mActionMode == null && !getClipboard().isMultiselect()) { if (!OpenExplorer.BEFORE_HONEYCOMB && OpenExplorer.USE_ACTIONMODE) { try { Method mStarter = getActivity().getClass().getMethod("startActionMode"); mActionMode = mStarter.invoke(getActivity(), new ActionModeHelper.Callback() { //@Override public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) { return false; } //@Override public void onDestroyActionMode(android.view.ActionMode mode) { mActionMode = null; mActionModeSelected = false; } //@Override public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.context_file, menu); menu.findItem(R.id.menu_context_paste).setEnabled(getClipboard().size() > 0); //menu.findItem(R.id.menu_context_unzip).setEnabled(mHoldingZip); mActionModeSelected = true; return true; } //@Override public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) { return executeMenu(item.getItemId(), mode, file); } }); Class cAM = Class.forName("android.view.ActionMode"); Method mST = cAM.getMethod("setTitle", CharSequence.class); mST.invoke(mActionMode, file.getName()); } catch (Exception e) { Logger.LogError("Error using ActionMode", e); } } return true; } return false; }
From source file:biz.wiz.android.wallet.ui.TransactionsListFragment.java
private void handleTransactionClick(@Nonnull final Transaction tx) { activity.startActionMode(new ActionMode.Callback() { private Address address; private byte[] serializedTx; private static final int SHOW_QR_THRESHOLD_BYTES = 2500; @Override/*from w w w. j ava2s .c o m*/ public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { final MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.wallet_transactions_context, menu); return true; } @Override public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { try { final Date time = tx.getUpdateTime(); final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity); final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity); mode.setTitle(time != null ? (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time)) + ", " + timeFormat.format(time) : null); final Coin value = tx.getValue(wallet); final boolean sent = value.signum() < 0; address = sent ? WalletUtils.getWalletAddressOfReceived(tx, wallet) : WalletUtils.getFirstFromAddress(tx); final String label; if (tx.isCoinBase()) label = getString(R.string.wallet_transactions_fragment_coinbase); else if (address != null) label = AddressBookProvider.resolveLabel(activity, address.toString()); else label = "?"; final String prefix = getString(sent ? R.string.symbol_to : R.string.symbol_from) + " "; if (tx.getPurpose() != Purpose.KEY_ROTATION) mode.setSubtitle(label != null ? prefix + label : WalletUtils.formatAddress(prefix, address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE)); else mode.setSubtitle(null); menu.findItem(R.id.wallet_transactions_context_edit_address).setVisible(address != null); serializedTx = tx.unsafeBitcoinSerialize(); menu.findItem(R.id.wallet_transactions_context_show_qr) .setVisible(serializedTx.length < SHOW_QR_THRESHOLD_BYTES); return true; } catch (final ScriptException x) { return false; } } @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { switch (item.getItemId()) { case R.id.wallet_transactions_context_edit_address: handleEditAddress(tx); mode.finish(); return true; case R.id.wallet_transactions_context_show_qr: handleShowQr(); mode.finish(); return true; case R.id.wallet_transactions_context_browse: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.EXPLORE_BASE_URL + "tx/" + tx.getHashAsString()))); mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(final ActionMode mode) { } private void handleEditAddress(@Nonnull final Transaction tx) { EditAddressBookEntryFragment.edit(getFragmentManager(), address.toString()); } private void handleShowQr() { final int size = getResources().getDimensionPixelSize(R.dimen.bitmap_dialog_qr_size); final Bitmap qrCodeBitmap = Qr.bitmap(Qr.encodeCompressBinary(serializedTx), size); BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); }