senzacionale
senzacionale

Reputation: 20916

Creatinng a custom Toast view

I want to create custom Toast view like

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

and in BroadcastReceiver on onReceive method

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

but no message is shown when the code is called. If i use Toast then text is shown. What i am doing wrong?

Upvotes: 1

Views: 1073

Answers (4)

Mahesh
Mahesh

Reputation: 2892

Use this code:

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

Upvotes: 0

Marek R
Marek R

Reputation: 38072

Did you see example form documentation?
Looks like not.
You do not need to extend Activity! Just use inflater and standard Toast, with setView API.

Upvotes: 1

Umesh
Umesh

Reputation: 4256

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

Do not extend the SMSToast class from an Activity. make it a simple java class.

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

Upvotes: 4

Atul Bhardwaj
Atul Bhardwaj

Reputation: 6717

Please change these two lines

 View layout = inflater.inflate(R.layout.toast_sms, null);
and
 Toast toast = new Toast(getApplicationContext());

Upvotes: 2

Related Questions