1

我想创建自定义 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,则会显示文本。我做错了什么?

4

4 回答 4

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);   
于 2012-08-13T11:36:46.290 回答
2

请更改这两行

 View layout = inflater.inflate(R.layout.toast_sms, null);
and
 Toast toast = new Toast(getApplicationContext());
于 2012-08-13T11:26:46.080 回答
1

您看到示例表单文档了吗?
好像没有。
您不需要扩展 Activity!只需使用充气机和标准Toast 以及 setView API

于 2012-08-13T11:52:10.527 回答
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();
于 2012-11-22T13:45:30.023 回答