How to access a view that is not running?
-
17-06-2021 - |
Question
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?
Solution
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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow