我想创建一个自定义的 Toast view:
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,text显示。
哪里出错呢?
SMSToast对象继承的是Activity,应该继承Toast
showToast里面LayoutInflater获取:
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
应该是这样了
直接写个自定义Toast类,什么都不要继承也可以
传递activity对象过来,在new的时候,或者单例方式