I am trying to use a toast from another class.
In class 1 I have the toast method:
public static void textToast(String textToDisplay)
{
Context context = getApplicationContext();
CharSequence text = textToDisplay;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER, 50, 50);
toast.show();
}
I am trying to call this toast from another class but when I make the method static, it says cannot make a static reference to this method getApplicationContext().
I access it by using class2.textToast("");
Any advice on this would be appreciated. Thanks
If you want to provide a method which should be valid for different contexts (eg activities), pass this context as parameter.
public static void textToast(String textToDisplay, Context context) { ... }
If you want to call this method from nested inner classes (as is often the case), you can use this
as context
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(or implement textToast
in the outer class and call it via OuterClass.this.textToast
from the nested inner class)
public void FlesmynToast(Activity fActivity, String fMessage) {
LayoutInflater fInflater = fActivity.getLayoutInflater();
View fView = fInflater.inflate(R.layout.custom_toast (ViewGroup) fActivity.findViewById(R.id.custom_toast_layout_id));
ImageView image = (ImageView) fView.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
TextView fText = (TextView) fView.findViewById(R.id.text);
fText.setText(fMessage);
// Toast...
Toast fToast = new Toast(fActivity.getApplicationContext());
fToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
fToast.setDuration(Toast.LENGTH_LONG);
fToast.setView(fView);
fToast.show();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.