Java Code Examples for com.google.android.material.snackbar.Snackbar#setAction()

The following examples show how to use com.google.android.material.snackbar.Snackbar#setAction() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseActivity.java    From Instagram-Profile-Downloader with MIT License 6 votes vote down vote up
@Override
public void showSnackBar(String message) {
    final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG);

    View snackbarView = snackbar.getView();
    snackbarView.setBackgroundColor(Color.WHITE);
    TextView textView = (TextView) snackbarView.findViewById(R.id.snackbar_text);
    textView.setTextColor(Color.BLACK);

    snackbar.setAction("OK", new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            snackbar.dismiss();
        }
    });
    snackbar.setActionTextColor(Color.BLACK);
    snackbar.show();
}
 
Example 2
Source File: CodeRecordsFragment.java    From SmsCode with GNU General Public License v3.0 6 votes vote down vote up
private void removeSelectedItems() {
    final List<SmsMsg> itemsToRemove = mCodeRecordAdapter.removeSelectedItems();
    String text = getString(R.string.some_items_removed, itemsToRemove.size());
    Snackbar snackbar = SnackbarHelper.makeLong(mRecyclerView, text);
    snackbar.addCallback(new Snackbar.Callback() {
        @Override
        public void onDismissed(Snackbar transientBottomBar, int event) {
            if (event != DISMISS_EVENT_ACTION) {
                try {
                    DBManager.get(mActivity).removeSmsMsgList(itemsToRemove);
                } catch (Exception e) {
                    XLog.e("Error occurs when remove SMS records", e);
                }
            }
        }
    });
    snackbar.setAction(R.string.revoke, v -> mCodeRecordAdapter.addItems(itemsToRemove));
    snackbar.show();

    mCurrentMode = RECORD_MODE_NORMAL;
    refreshActionBarByMode();
}
 
Example 3
Source File: DetailsActivity.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
protected void onPostExecute(final Boolean success) {
    if (this.dialog.isShowing()) {
        this.dialog.dismiss();
    }

    if (!success) {
        Toast.makeText(DetailsActivity.this, R.string.export_failed, Toast.LENGTH_SHORT).show();
        return;
    }

    // Export successful, ask user to further share file!
    View v = findViewById(R.id.view_pager);
    Snackbar s = Snackbar.make(v, R.string.exported, Snackbar.LENGTH_LONG);
    s.setAction(R.string.share_csv, v1 -> shareExport());
    s.setActionTextColor(getResources().getColor(R.color.colorPrimary));
    s.show();
}
 
Example 4
Source File: ProfileActivity.java    From loco-answers with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
    if (viewHolder instanceof ProfileAdapter.MyViewHolder) {
        final int deletedIndex = viewHolder.getAdapterPosition();
        final Profile deletedProfile = profiles.get(deletedIndex);

        String name = deletedProfile.getName();
        final ProfileEntity deletedEntity = profileFromEntity(deletedProfile);
        // deletedEntity.setUid()
        mProfileAdapter.removeProfile(deletedIndex);

        deleteDataFromDB(deletedEntity);

        Snackbar snackbar = Snackbar.make(coordinatorLayout, name + " removed from list", Snackbar.LENGTH_LONG);
        snackbar.setAction("UNDO", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProfileAdapter.restoreProfile(deletedProfile, deletedIndex);
                insertDataToDB(deletedEntity);
            }
        });
        snackbar.show();

    }
}
 
Example 5
Source File: LazyMainActivity.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
private Snackbar setupSnackbar() {
    String responseMessage = getResources().getString(R.string.no_server_response_message);
    String actionString = getResources().getString(R.string.no_server_response_action);
    Snackbar snackbar = Snackbar
            .make(mRecyclerView, responseMessage, Snackbar.LENGTH_LONG);
    snackbar.setAction(actionString, v -> scrollToTopAndRefresh());

    return snackbar;
}
 
Example 6
Source File: SnackbarUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 设置 Action 按钮文字内容及点击监听
 * @param listener 按钮点击事件
 * @param resId    R.string.id
 * @param objs     格式化参数
 * @return {@link SnackbarUtils}
 */
public SnackbarUtils setAction(final View.OnClickListener listener, @StringRes final int resId, final Object... objs) {
    Snackbar snackbar = getSnackbar();
    if (snackbar != null) {
        String content = AppCommonUtils.getFormatRes(resId, objs);
        if (!TextUtils.isEmpty(content)) {
            snackbar.setAction(content, listener);
        }
    }
    return this;
}
 
Example 7
Source File: MainActivity.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused") // it's actually used, just injected by Butter Knife
@OnClick(R.id.fab)
void onClick() {
    Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
    if (fragment instanceof OverviewBaseFragment) {
        ((OverviewBaseFragment) fragment).showRandomComic();
    } else if (fragment instanceof ComicFragment) {
        if (prefHelper.showRandomTip()) {
            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), R.string.random_tip, BaseTransientBottomBar.LENGTH_LONG);
            snackbar.setAction(R.string.got_it, view -> prefHelper.setShowRandomTip(false));
            snackbar.show();
        }
        ((ComicFragment) fragment).getRandomComic();
    }
}
 
Example 8
Source File: IndieAuthActivity.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (Intent.ACTION_VIEW.equals(intent.getAction())) {

        Snackbar.make(layout, getString(R.string.validating_code), Snackbar.LENGTH_SHORT).show();

        // Get the code and state.
        String code = intent.getData().getQueryParameter("code");
        String returnedState = intent.getData().getQueryParameter("state");
        if (code != null && code.length() > 0 && returnedState != null && returnedState.length() > 0) {
            validateCode(code, returnedState);
        }
        else {
            final Snackbar snack = Snackbar.make(layout, getString(R.string.no_code_found), Snackbar.LENGTH_INDEFINITE);
            snack.setAction(getString(R.string.close), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        snack.dismiss();
                    }
                }
            );
            snack.show();
        }
    }
}
 
Example 9
Source File: Base.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void OnFailureRequest(VolleyError error) {
    hideProgressBar();
    String message = Utility.parseNetworkError(error, getApplicationContext(), R.string.media_network_fail, R.string.media_fail);
    final Snackbar snack = Snackbar.make(layout, message, Snackbar.LENGTH_INDEFINITE);
    snack.setAction(getString(R.string.close), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snack.dismiss();
            }
        }
    );
    snack.show();
}
 
Example 10
Source File: ExperimentListFragment.java    From science-journal with Apache License 2.0 5 votes vote down vote up
public void showSnackbar(String message, @Nullable View.OnClickListener undoOnClickListener) {
  if (isParentGone()) {
    return;
  }
  Snackbar bar =
      AccessibilityUtils.makeSnackbar(
          parentReference.get().getView(), message, Snackbar.LENGTH_LONG);
  if (undoOnClickListener != null) {
    bar.setAction(R.string.action_undo, undoOnClickListener);
  }
  snackbarManager.showSnackbar(bar);
}
 
Example 11
Source File: AddressBookDemoActivity.java    From StickyHeaders with MIT License 5 votes vote down vote up
@Override
public void onRandomUserLoadFailure(final Throwable t) {
    Log.e(TAG, "onRandomUserLoadFailure: Unable to load people, e:" + t.getLocalizedMessage());

    progressBar.setVisibility(View.GONE);
    recyclerView.setVisibility(View.GONE);

    Snackbar snackbar = Snackbar.make(recyclerView, "Unable to load addressbook", Snackbar.LENGTH_LONG);
    snackbar.setAction(R.string.demo_addressbook_load_error_action, v -> showRandomUserLoadError(t.getLocalizedMessage()));
    snackbar.show();
}
 
Example 12
Source File: LibraryFragment.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private void redownloadContent(@NonNull final List<Content> contentList, boolean reparseImages) {
    StatusContent targetImageStatus = reparseImages ? StatusContent.ERROR : null;
    for (Content c : contentList) viewModel.addContentToQueue(c, targetImageStatus);

    if (Preferences.isQueueAutostart())
        ContentQueueManager.getInstance().resumeQueue(getContext());

    String message = getResources().getQuantityString(R.plurals.add_to_queue, contentList.size(), contentList.size());
    Snackbar snackbar = Snackbar.make(recyclerView, message, BaseTransientBottomBar.LENGTH_LONG);
    snackbar.setAction("VIEW QUEUE", v -> viewQueue());
    snackbar.show();
}
 
Example 13
Source File: SnackbarUtil.java    From weather with Apache License 2.0 5 votes vote down vote up
/**
 * Show the snackbar.
 */
public Snackbar show() {
  final View view = this.view;
  if (view == null) return null;
  if (messageColor != COLOR_DEFAULT) {
    SpannableString spannableString = new SpannableString(message);
    ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor);
    spannableString.setSpan(
        colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );
    sReference = new WeakReference<>(Snackbar.make(view, spannableString, duration));
  } else {
    sReference = new WeakReference<>(Snackbar.make(view, message, duration));
  }
  final Snackbar snackbar = sReference.get();
  final View snackbarView = snackbar.getView();
  if (bgResource != -1) {
    snackbarView.setBackgroundResource(bgResource);
  } else if (bgColor != COLOR_DEFAULT) {
    snackbarView.setBackgroundColor(bgColor);
  }
  if (bottomMargin != 0) {
    ViewGroup.MarginLayoutParams params =
        (ViewGroup.MarginLayoutParams) snackbarView.getLayoutParams();
    params.bottomMargin = bottomMargin;
  }
  if (actionText.length() > 0 && actionListener != null) {
    if (actionTextColor != COLOR_DEFAULT) {
      snackbar.setActionTextColor(actionTextColor);
    }
    snackbar.setAction(actionText, actionListener);
  }
  snackbar.show();
  return snackbar;
}
 
Example 14
Source File: HelperUtils.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
public static void showError(String message, CoordinatorLayout coordinatorLayout) {
    final Snackbar snackbar = Snackbar
            .make(coordinatorLayout, message, Snackbar.LENGTH_INDEFINITE);
    snackbar.setAction(R.string.actionDismiss, view -> snackbar.dismiss());
    TextView snackbarTextView = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
    snackbarTextView.setMaxLines(99);
    snackbar.show();
}
 
Example 15
Source File: LazyMainActivity.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 5 votes vote down vote up
private Snackbar setupSnackbar() {
	String responseMessage = getResources().getString(R.string.no_server_response_message);
	String actionString = getResources().getString(R.string.no_server_response_action);
	Snackbar snackbar = Snackbar
			.make(mRecyclerView, responseMessage, Snackbar.LENGTH_LONG);
	snackbar.setAction(actionString, new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			scrollToTopAndRefresh();
		}
	});

	return snackbar;
}
 
Example 16
Source File: MainActivity.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
private void checkClipboardUrlInternal() {
    String text = getTextFromClipboard();
    int hashCode = text != null ? text.hashCode() : 0;

    if (text != null && hashCode != 0 && Settings.getClipboardTextHashCode() != hashCode) {
        Announcer announcer = createAnnouncerFromClipboardUrl(text);
        if (announcer != null && mDrawerLayout != null) {
            Snackbar snackbar = Snackbar.make(mDrawerLayout, R.string.clipboard_gallery_url_snack_message, Snackbar.LENGTH_INDEFINITE);
            snackbar.setAction(R.string.clipboard_gallery_url_snack_action, v -> startScene(announcer));
            snackbar.show();
        }
    }

    Settings.putClipboardTextHashCode(hashCode);
}
 
Example 17
Source File: MessagesActivity.java    From android with MIT License 5 votes vote down vote up
private void showDeletionSnackbar() {
    View view = swipeRefreshLayout;
    Snackbar snackbar = Snackbar.make(view, R.string.snackbar_deleted, Snackbar.LENGTH_LONG);
    snackbar.setAction(R.string.snackbar_undo, v -> undoDelete());
    snackbar.addCallback(new SnackbarCallback());
    snackbar.show();
}
 
Example 18
Source File: CourseOutlineFragment.java    From edx-app-android with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
        case R.id.item_delete:
            final int checkedItemPosition = listView.getCheckedItemPosition();
            // Change the icon to download icon immediately
            final View rowView = listView.getChildAt(checkedItemPosition - listView.getFirstVisiblePosition());
            if (rowView != null) {
                // rowView will be null, if the user scrolls away from the checked item
                ((IconImageView) rowView.findViewById(R.id.bulk_download)).setIcon(FontAwesomeIcons.fa_download);
            }

            final CourseOutlineAdapter.SectionRow rowItem = adapter.getItem(checkedItemPosition);
            final List<CourseComponent> videos = rowItem.component.getVideos(true);
            final int totalVideos = videos.size();

            if (isOnCourseOutline) {
                environment.getAnalyticsRegistry().trackSubsectionVideosDelete(
                        courseData.getCourse().getId(), rowItem.component.getId());
            } else {
                environment.getAnalyticsRegistry().trackUnitVideoDelete(
                        courseData.getCourse().getId(), rowItem.component.getId());
            }

            /*
            The android docs have NOT been updated yet, but if you jump into the source code
            you'll notice that the parameter to the method setDuration(int duration) can
            either be one of LENGTH_SHORT, LENGTH_LONG, LENGTH_INDEFINITE or a custom
            duration in milliseconds.
            https://stackoverflow.com/a/30552666
            https://github.com/material-components/material-components-android/commit/2cb77c9331cc3c6a5034aace0238b96508acf47d
             */
            @SuppressLint("WrongConstant")
            final Snackbar snackbar = Snackbar.make(listView,
                    getResources().getQuantityString(R.plurals.delete_video_snackbar_msg, totalVideos, totalVideos),
                    SNACKBAR_SHOWTIME_MS);
            snackbar.setAction(R.string.label_undo, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // No need of implementation as we'll handle the action in SnackBar's
                    // onDismissed callback.
                }
            });
            snackbar.addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
                @Override
                public void onDismissed(Snackbar transientBottomBar, int event) {
                    super.onDismissed(transientBottomBar, event);
                    // SnackBar is being dismissed by any action other than its action button's press
                    if (event != DISMISS_EVENT_ACTION) {
                        final IStorage storage = environment.getStorage();
                        for (CourseComponent video : videos) {
                            final VideoBlockModel videoBlockModel = (VideoBlockModel) video;
                            final DownloadEntry downloadEntry = videoBlockModel.getDownloadEntry(storage);
                            if (downloadEntry.isDownloaded()) {
                                // This check is necessary because, this callback gets
                                // called multiple times when SnackBar is about to dismiss
                                // and the activity finishes
                                storage.removeDownload(downloadEntry);
                            } else {
                                return;
                            }
                        }
                    } else {
                        if (isOnCourseOutline) {
                            environment.getAnalyticsRegistry().trackUndoingSubsectionVideosDelete(
                                    courseData.getCourse().getId(), rowItem.component.getId());
                        } else {
                            environment.getAnalyticsRegistry().trackUndoingUnitVideoDelete(
                                    courseData.getCourse().getId(), rowItem.component.getId());
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            snackbar.show();
            mode.finish();
            return true;
        default:
            return false;
    }
}
 
Example 19
Source File: SensorFragment.java    From science-journal with Apache License 2.0 4 votes vote down vote up
private void doVisualAlert(SensorTrigger trigger) {
  final SensorCardPresenter presenter = getPresenterById(trigger.getSensorId());
  if (presenter == null) {
    return;
  }

  // In any of the presenter is visible, go ahead and pass the trigger to it.
  presenter.onSensorTriggerFired();

  // Only need to do a snackbar for off-screen visual alerts.
  if (!trigger.hasAlertType(TriggerInformation.TriggerAlertType.TRIGGER_ALERT_VISUAL)) {
    return;
  }
  // If a snackbar is already being shown, don't show a new one.
  if (snackbarManager.snackbarIsVisible()) {
    return;
  }

  // TODO: Work with UX to tweak this check so that the right amount of the card is shown.
  // Look to see if the card is outside of the visible presenter range. The alert is shown
  // near the top of the card, so we check between the first fully visible card and the last
  // partially visible card.
  if (!presenter.isTriggerBarOnScreen()) {

    SensorAppearance appearance =
        AppSingleton.getInstance(getActivity())
            .getSensorAppearanceProvider(getAppAccount())
            .getAppearance(trigger.getSensorId());
    String units = appearance.getUnits(getActivity());
    String sensorName = appearance.getName(getActivity());
    String triggerWhenText =
        getActivity()
            .getResources()
            .getStringArray(R.array.trigger_when_list_note_text)[
            trigger.getTriggerWhen().getNumber()];
    String message =
        getActivity()
            .getResources()
            .getString(
                R.string.trigger_snackbar_auto_text,
                sensorName,
                triggerWhenText,
                trigger.getValueToTrigger(),
                units);
    final Snackbar bar =
        AccessibilityUtils.makeSnackbar(getView(), message, Snackbar.LENGTH_LONG);
    bar.setAction(
        R.string.scroll_to_card,
        v -> {
          sensorCardLayoutManager.scrollToPosition(getPositionOfPresenter(presenter));
        });
    snackbarManager.showSnackbar(bar);
  }
}
 
Example 20
Source File: DeletedLabel.java    From science-journal with Apache License 2.0 4 votes vote down vote up
public void deleteAndDisplayUndoBar(
    View view,
    AppAccount appAccount,
    final Experiment experiment,
    LabelListHolder labelHolder,
    Runnable uiChangeOnUndo) {
  Context context = view.getContext();
  final DataController dc = AppSingleton.getInstance(context).getDataController(appAccount);
  Snackbar bar =
      AccessibilityUtils.makeSnackbar(
          view, context.getResources().getString(R.string.snackbar_note_deleted), UNDO_DELAY_MS);

  RxEvent undoneEvent = new RxEvent();

  // On undo, re-add the item to the database and the pinned note list.
  bar.setAction(
      R.string.snackbar_undo,
      new View.OnClickListener() {
        boolean undone = false;

        @Override
        public void onClick(View v) {
          if (this.undone) {
            return;
          }
          undoneEvent.onHappened();
          this.undone = true;
          labelHolder.addLabel(experiment, label);

          dc.updateExperiment(
              experiment.getExperimentId(),
              new LoggingConsumer<Success>(TAG, "re-add deleted label") {
                @Override
                public void success(Success value) {
                  uiChangeOnUndo.run();
                }
              });
        }
      });
  bar.show();

  // Add just a bit of extra time to be sure
  long delayWithBuffer = (long) (bar.getDuration() * 1.1);

  Context appContext = view.getContext().getApplicationContext();
  Observable.timer(delayWithBuffer, TimeUnit.MILLISECONDS)
      .takeUntil(undoneEvent.happens())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(o -> assetDeleter.accept(appContext));
}