2012-08-13 45 views
1

我想上的onReceive方法Creatinng定製吐司視圖

SMSToast toast = new SMSToast(); 
         toast.showToast(context, 
             "Received SMS from: " + msg_from + 
             " Content: " + msgBody); 

創建像

public class SMSToast extends Activity { 

    public void showToast(Context context, 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.toast_sms_text); 
     text.setText(message); 

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

和在廣播接收器的定製吐司視圖但是當代碼被稱爲沒有顯示消息。如果我使用Toast,則會顯示文字。我做錯了什麼?

+0

SMSToast吐司=新SMSToast(); toast.showToast(context,msg);這可能以這種方式調用活動的方法嗎? – 2012-08-13 11:42:11

回答

4
public class SMSToast{ 

    public void showToast(Context context, String message) { 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View layout = inflater.inflate(R.layout.toast_sms, null); 
     TextView text = (TextView) layout.findViewById(R.id.toast_sms_text); 
     text.setText(message); 
     Toast toast = new Toast(context); 
     toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
     toast.setDuration(Toast.LENGTH_LONG); 
     toast.setView(layout); 
     toast.show(); 
    } 
} 

不要從活動擴展SMSToast類。使其成爲一個簡單的java類。

SMSToast toast = new SMSToast();       
toast.showToast(context, "Received SMS from: " + msg_from + 
" Content: " + msgBody); 
+0

+1爲完美答案。 – rajpara 2012-08-13 11:43:51

+0

此SMSToast類不是必需的或showToast應該是靜態的。無論如何,沒有理由鍵入,文檔給出了完美的例子,這是非常相似的。 – 2012-08-13 11:54:19

2

請更改這兩個行

View layout = inflater.inflate(R.layout.toast_sms, null); 
and 
Toast toast = new Toast(getApplicationContext()); 
1

你見過example form documentation嗎?
看起來不像。
您無需擴展活動!只需使用inflater和標準Toast, with setView API

+0

如果不擴展Activity類,getLayoutInflater不起作用。所以我不能在擴展BroadcastReceiver的類中使用它... – senzacionale 2012-08-13 12:53:59

+0

5秒的文檔搜索:'LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)''。上下文在BroadcastReceiver中可用。 – 2012-08-13 12:58:06

+0

這段代碼是正確的。對不起,我不知道這個... – senzacionale 2012-08-13 13:01:21

0

使用此代碼:

LayoutInflater mInflater=LayoutInflater.from(context); 

View view=mInflater.inflate(R.layout.your_layout_file,null); 
Toast toast=new Toast(context); 
toast.setView(view); 
toast.setDuration(TOAST.LENGTH_LONG); 
toast.show();