olfek
olfek

Reputation: 3520

How to make toast work in a class which doesn't extend activity?

How do I make this

Toast.makeText(this,"Please enter a Number",Toast.LENGTH_LONG).show();

work in a class which only

implements OnClickListener

How can I make it work without adding

extends Activity

The class its in is called

ButtonClickListener

which is called from the MainActivity

Upvotes: 1

Views: 652

Answers (3)

babis
babis

Reputation: 228

public class ButtonClickListener implements OnClickListener {
      ...
      private Context context;
      ...

      public ButtonClickListener(..., Context c) {
         ...
         context = c;
      }

     ...
     void showToast(String text) {
         Toast.makeText(context, text, Toast.LENGTH_LONG).show();
     }
}

and in your MainActivity.java use this

CustomOnClickListener xyz = new CustomOnClickListener(...,MainActivity.this);
xyz.showToast("Please enter a Number");

Upvotes: 2

Ravi Kant
Ravi Kant

Reputation: 830

you can show toast by context

Toast.makeText(context,"Please enter a Number",Toast.LENGTH_LONG).show();

just pass the context to constructor of ButtonClickListener and use that context.

Upvotes: 1

hmartinezd
hmartinezd

Reputation: 1186

In order to do that, your ButtonClickListener class needs to have a Context value, and once you create an instance of that class in the MainActivity, you have to pass the Context. Maybe set a ButtonClickListener constructor that requires a Context.

Upvotes: 0

Related Questions