Alex_89
Alex_89

Reputation: 131

Setting OnClickListener on SnackBar not setAction()?

I am trying to find out how can I get snackbar to to have an onClickListener. here is a simple code:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            snackbar.make(v, "This is a snackBar", Snackbar.LENGTH_LONG)
                    .setTextColor(Color.BLUE)
                    .show();
        }
    });

I know about setAction() but I want snackBar itself be my click button. I know new androidx support library has changed so many of the solutions I found online are not useful anymore.

EDIT: Why this piece of code does not work with it?

View view = snackbar.getView();
    TextView text = view.findViewById(com.google.android.material.R.id.snackbar_text);
    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          
        }
    });

I Have fixed my problem by coding the snackbar object inside the onClickListner() instead of introduced as a field object. Apparently my main issue was related to this chnage.

Upvotes: 1

Views: 155

Answers (1)

LppEdd
LppEdd

Reputation: 21134

If by snackbar you mean android.support.design.widget.Snackbar, then you might want to use the addCallback method, to be notified on dismissal.

snackbar.addCallback(new Snackbar.Callback() {
  @Override
  public void onDismissed(final Snackbar snackbar, final int event) {
    ...
  }
});

Compare the event parameter with the static constants to understand how it was dismissed.

Upvotes: 1

Related Questions