2009-10-24 29 views
5

我不知道有人能幫助我。我試圖在收到短信時顯示一個toast元素。這敬酒應包含具有圖像(SMS圖標)和2個textviewsShow Broadcast Toast來自BroadcastReceiver

如果我把從活動下面的方法,它按預期工作(發件人,消息)的佈局......

public void showToast(Context context, String name, String message) { 
    LayoutInflater inflater = getLayoutInflater(); 
    View layout = inflater.inflate(R.layout.toast_sms, 
            (ViewGroup) findViewById(R.id.toast_sms_root)); 

    TextView text = (TextView) layout.findViewById(R.id.toastsms_text); 
    text.setText(message); 

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

但是,如果我試圖從我SMSReceiver調用以同樣的方式相同的代碼,我得到:

The method getLayoutInflater() is undefined for the type SmsReceiver 
The method findViewById(int) is undefined for the type SmsReceiver 
The method getApplicationContext() is undefined for the type SmsReceiver 

可有人請告知我如何從一個意圖做tihs。我認爲這個問題與跨線程有關,但我不確定如何繼續。我見過一些例子在線,但他們似乎要麼使用過時的代碼或只顯示簡單的文本

可有人請點我在正確的方向

非常感謝

+0

任何理由/爲downvote建設性的批評? – Basic 2013-08-05 16:28:04

回答

10

您可以使用LayoutInflater.from(上下文)來獲取您的LayoutInflater。就像這樣:

LayoutInflater mInflater = LayoutInflater.from(context); 
View myView = mInflater.inflate(R.layout.customToast, null); 
TextView sender = (TextView) myView.findViewById(R.id.sender); 
TextView message = (TextView) myView.findViewById(R.id.message); 
+1

這樣做,非常感謝:) – Basic 2009-10-27 12:32:35

7

你的編譯錯誤是因爲BroadcastReceiver不會從Context繼承。使用傳入onReceive()Context(並刪除getApplicationContext() - 只需使用您通過的Context)。

現在,這可能仍然不行,因爲我不知道你是否能提高從首位BroadcastReceiver一個Toast,但是這將至少讓你過去編譯錯誤。

+0

謝謝我現在嘗試 – Basic 2009-10-24 21:49:36

+0

好吧,我現在正在做新的吐司(上下文),但它還沒有解決其他2編譯錯誤 - getLayoutInflater和findViewById。我如何參考/實例化這些? – Basic 2009-10-24 21:52:13

+0

findViewById()只存在於Activity中。作爲第二個參數傳遞給layout()調用。要獲取LayoutInflater,請參閱SDK中LayoutInflater的文檔。 – CommonsWare 2009-10-24 22:11:53

2

舉杯可以創建並從活動或服務展示,而不是廣播接收器

+0

發現困難的方式。 – 2012-02-23 08:02:55

+0

不,可以從廣播接收器顯示吐司,它對我很有用,所以它是可能的。 – 2013-10-02 14:05:07