我想知道是否有人可以帮助我。我正在尝试在收到短信时显示一个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();
}

但是,如果我尝试从我的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

有人可以告诉我如何从意图中做到这一点。我认为这个问题与跨线程有某种关系,但我不确定如何继续。我在网上看过几个例子,但他们似乎要么使用已弃用的代码,要么只显示简单的文本

有人可以指出我正确的方向吗

非常感谢

有帮助吗?

解决方案

您可以使用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);

其他提示

您的编译错误是因为 BroadcastReceiver 不从 Context 继承。使用传递到 onReceive() Context (并摆脱 getApplicationContext() - 只需使用 Context 你被通过了。

现在,这可能不起作用,因为我不确定你是否可以从 BroadcastReceiver 首先提出 Toast ,但这至少会让你超越编译错误。

可以从活动或服务创建和显示Toast,而不是广播接收器

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top