我想创建自定义Toast视图,如
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();
}
}
和onReceive方法中的BroadcastReceiver
SMSToast toast = new SMSToast();
toast.showToast(context,
"Received SMS from: " + msg_from +
" Content: " + msgBody);
但调用代码时不显示任何消息。如果我使用Toast,则显示文本。我做错了什么?
答案 0 :(得分: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();
}
}
不要从Activity扩展SMSToast类。使它成为一个简单的java类。
SMSToast toast = new SMSToast();
toast.showToast(context, "Received SMS from: " + msg_from +
" Content: " + msgBody);
答案 1 :(得分:2)
请更改这两行
View layout = inflater.inflate(R.layout.toast_sms, null);
and
Toast toast = new Toast(getApplicationContext());
答案 2 :(得分:1)
您看到了example form documentation吗?
看起来不是。
你不需要扩展Activity!只需使用inflater和标准Toast, with setView API。
答案 3 :(得分: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();