Bas*_*sic 5 user-interface android dalvik toast
我想知道是否有人可以帮助我.我正在尝试在收到短信时显示一个toast元素.此吐司应包含具有图像(SMS图标)和2个文本视图(发件人,消息)的布局
如果我从一个活动调用以下方法,它按预期工作...
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();
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试从我的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
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何从意图中做到这一点.我认为这个问题与跨线程有某种关系,但我不确定如何继续.我在网上看过几个例子,但他们似乎要么使用已弃用的代码,要么只显示简单的文本
有人可以指出我正确的方向
非常感谢
Tim*_*m H 11
您可以使用LayoutInflater.from(context)来获取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);
Run Code Online (Sandbox Code Playgroud)
您的编译错误是因为BroadcastReceiver不继承Context.使用Context传入的onReceive()(并摆脱getApplicationContext()- 只需使用Context你传递的).
现在,这可能仍然不起作用,因为我不确定你是否可以Toast从一开始就提出a BroadcastReceiver,但这至少会让你超过编译错误.
| 归档时间: |
|
| 查看次数: |
10105 次 |
| 最近记录: |