2

I am trying to providing click listener to toast message.Any one tell me is it possible to provide click listener to Toast in android?

I am using custom view for toast and I am apply onclick listener to my view it's not working.I triade this

LayoutInflater inflater = (LayoutInflater) ConnectToXMPP.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View layout = inflater.inflate(R.layout.chat_message_alert_dialog,null);
TextView text = (TextView) layout.findViewById(R.id.chat_popup_message_textview);
text.setText("From : " + fromName+ "\n" + fromName);
LinearLayout chatMessageLayout = (LinearLayout)    
layout.findViewById(R.id.chat_popup_message_layout);

Toast toast = new Toast(ConnectToXMPP.mContext);
toast.setView(layout);
toast.setGravity(Gravity.CENTER_VERTICAL, 0,0);
toast.setDuration(60000);
toast.getView().setClickable(true);
toast.getView().setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

     Toast.makeText(ConnectToXMPP.mContext,"toast touched",Toast.LENGTH_SHORT).show();

}
});
toast.show();
Android_dev
  • 320
  • 1
  • 7
  • 26

4 Answers4

5

Use snack bar for this purpose.

Snackbar.make(findViewById(android.R.id.content), "Hi I'm snack bar", Snackbar.LENGTH_LONG)
            .setTextColor(Color.parseColor("#FFFFFF"))
            .setDuration(30000)
            .setBackgroundTint(Color.parseColor("#716E7C"))
            .setActionTextColor(Color.parseColor("#49FF00"))
            .setAction("Refresh") {
                // Do whatever you want
            }.show()
Waqar Ahmed
  • 349
  • 4
  • 11
1

Janusz's Answer

A toast can not be clicked. It is not possible to capture a click inside a toast message. You will need to build a dialog for that. Look at Creating Dialogs for more info.

The API on the Toast class state that a toast will never receive the focus and because a toast is not a view there is no onClick message. I would assume that therefore childs of a Toast can not be clicked as well.

Community
  • 1
  • 1
Muhammad Zahid
  • 607
  • 1
  • 7
  • 17
  • I have been looking for this confirmation. I always thought Toast would receive click events. I could not find documentation that states it. – Farruh Habibullaev Feb 11 '20 at 00:24
1

Have a look at John Persanos SuperToast library. It includes clickable toasts. Github repo

Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34
1

You can provide the ID to root view of the XML layout file. And find it from the layout by using FindviewbyId and then you can configure the listener for it