[英]A linked list in another class accessible from one method but not from another
[英]Allow toast to be accessible from another class
我正在嘗試使用另一堂課的吐司。
在第1課中,我有toast方法:
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();
}
我試圖從另一個類中調用此Toast,但是當我將該方法設為靜態時,它說無法對該方法getApplicationContext().
進行靜態引用getApplicationContext().
我通過使用class2.textToast("");
訪問它
任何建議,將不勝感激。 謝謝
如果要提供對不同上下文(例如活動)有效的方法,請將此上下文作為參數傳遞。
public static void textToast(String textToDisplay, Context context) { ... }
如果要從嵌套內部類中調用此方法(通常是這樣),則可以this
用作上下文
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(或實現textToast
在外類,並通過調用它OuterClass.this.textToast
從嵌套內部類)
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.