0

I tried to add onClick to my custom toast button, but the button doesn't work. Please I need help

final Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
View custom_view = getLayoutInflater().inflate(R.layout.search_snackbar, null);

Button action = custom_view.findViewById(R.id.sb_action);
action.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View p1) {
        //run code on click
    }

 });

toast.setGravity(Gravity.FILL_HORIZONTAL|Gravity.BOTTOM, 0, 0);
toast.setView(custom_view);
toast.show();

Image of my custom toast with button :

Image of my custom toast with button

Shay Kin
  • 2,539
  • 3
  • 15
  • 22
  • Hi, ToastMessages are not clickable, they provides feedback about something. If you want any user interaction, you should use Snackbars instead of Toasts. Details: https://developer.android.com/guide/topics/ui/notifiers/toasts – tugceaktepe Apr 28 '21 at 22:12
  • https://stackoverflow.com/questions/24653152/is-it-possible-to-create-a-clickable-toast-like-notification – Amir Kateb Apr 28 '21 at 23:07
  • This question has already been discussed https://stackoverflow.com/questions/24653152/is-it-possible-to-create-a-clickable-toast-like-notification – Amir Kateb Apr 28 '21 at 23:09
  • Does this answer your question? [Is it possible to create a clickable Toast-like notification?](https://stackoverflow.com/questions/24653152/is-it-possible-to-create-a-clickable-toast-like-notification) – impo Apr 29 '21 at 05:33

1 Answers1

0

As noted in the comments, you could consider the using a SnackBar from the Material design library.

But if you don't want the overhead of the support library, you could use the hack below

    try {
            Class<?> c = Class.forName("android.widget.Toast");
            Method method = c.getDeclaredMethod("getWindowParams");
            WindowManager.LayoutParams param = (WindowManager.LayoutParams) method.invoke(toast);
            param.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        } catch (Exception e) {
            e.printStackTrace();
        }

Tested on Android Nougat

Mab
  • 412
  • 3
  • 12