2014-01-31 20 views
1

我希望能夠調用Utills類的方法在屏幕上彈出自定義Toast消息。Utills類的自定義Toast

我的代碼:

static public void ShowToast(Context context,String message, int duration) 
{ 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    // Inflate the Layout 
    View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.custom_toast_layout)); 

    TextView text = (TextView) layout.findViewById(R.id.textToShow); 
    // Set the Text to show in TextView 
    text.setText(message); 

    Toast toast = new Toast(context); 
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
    toast.setDuration(duration); 
    toast.setView(layout); 
    toast.show(); 
} 

我有4行,其中i調用

(ViewGroup) findViewById(R.id.custom_toast_layout) 

我有其中規定一個編譯錯誤一個proble:

方法findViewById(INT )未定義爲類型SystemUtills

我該如何解決這個問題?

謝謝。

+0

參考http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView%20。 –

回答

3

findViewById是活動的方法,所以在這條線上

View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.custom_toast_layout)); 

你需要context.findViewById(R.id.custom_toast_layout)

這對於編譯時錯誤的原因。

+0

我試過了,它給出:「方法findViewById(int)是未定義的類型上下文」任何想法whay? –

+1

findViewById是Activity的一種方法,而不是Context的方法。如果您從Activity調用ShowToast並傳遞「this」作爲參數,則可以將上下文轉換爲活動:((Activity)context).findViewById – Blackbelt

+0

好吧,添加一個(ViewGroup)強制類型以開始參數及其工作。 –