gpt4 book ai didi

android - 创建自定义 Toast View

转载 作者:行者123 更新时间:2023-11-29 14:40:19 25 4
gpt4 key购买 nike

我想像这样创建自定义 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();
}
}

并在 BroadcastReceiver 的 onReceive 方法中

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

但是调用代码时没有显示任何消息。如果我使用 Toast,则会显示文本。我做错了什么?

最佳答案

 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);

关于android - 创建自定义 Toast View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11933237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com