Question

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

Was it helpful?

Solution 3

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.

OTHER TIPS

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");

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top