0

So I've used this tutorial to create a custom toast, that will display an image.

Now what I want to do is be able to pass in an image resource and tell my toast method to display that image.

So I've got this:

 private void callToast(int image_resource)
{               
    LayoutInflater inflater = getLayoutInflater();
    View v = inflater.inflate(R.layout.mycustomtoast, (ViewGroup) findViewById(R.id.toast_layout));

    /*set the image*/           
    ImageView iv = (ImageView)findViewById(R.id.toast_iv);
    iv.setImageResource(image_resource); 

    Toast t = new Toast(this);
    t.setView(v);
    t.setGravity(Gravity.CENTER,0,0); 

    t.show();  
}

now findViewById returns null... I understand because the XML it's under isn't being used?

How do I change the custom toast image view's source?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194

1 Answers1

2

here you forgot to view refrence v

ImageView iv = (ImageView)v.findViewById(R.id.toast_iv);

Solution

Toast t = new Toast(this);
t.setView(v);

ImageView iv = (ImageView)v.findViewById(R.id.toast_iv);
iv.setImageResource(image_resource); 

t.setGravity(Gravity.CENTER,0,0); 
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • Thanks. I guess I'm a little confused about the usage of findViewById - as you can usually use it by itself (without attaching it to a view object). When you use it by itself does it just search the xml of the current activity? – dwjohnston Jun 26 '12 at 06:28