Is it possible to programmatically add an image to a toast popup?
There's always the possibility to create a custom layout. There was one fact which I disliked about that: It breaks the system default toast UI. This could differ on different platforms and implementations. There's no simple way to use the system default resource so I decided to hack the toast and force an image into it.
Hint: You can get the default resource like this:
Toast.makeToast(context, "", 0).getView().getBackground()
Here's a helper which will display an image in front of the toast message:
Helper.makeImageToast(context, R.drawable.my_image, "Toast with image", Toast.LENGTH_SHORT).show()
I use that to indicate success, info or error. Makes a toast information nicer and more expressive...
(It's worth mentioning that the hack bases on the fact that the internal toast is using a LinearLayout so isn't system and implementation independent. See comments.)
public static Toast makeImageToast(Context context, int imageResId, CharSequence text, int length) {
Toast toast = Toast.makeText(context, text, length);
View rootView = toast.getView();
LinearLayout linearLayout = null;
View messageTextView = null;
// check (expected) toast layout
if (rootView instanceof LinearLayout) {
linearLayout = (LinearLayout) rootView;
if (linearLayout.getChildCount() == 1) {
View child = linearLayout.getChildAt(0);
if (child instanceof TextView) {
messageTextView = (TextView) child;
}
}
}
// cancel modification because toast layout is not what we expected
if (linearLayout == null || messageTextView == null) {
return toast;
}
ViewGroup.LayoutParams textParams = messageTextView.getLayoutParams();
((LinearLayout.LayoutParams) textParams).gravity = Gravity.CENTER_VERTICAL;
// convert dip dimension
float density = context.getResources().getDisplayMetrics().density;
int imageSize = (int) (density * 25 + 0.5f);
int imageMargin = (int) (density * 15 + 0.5f);
// setup image view layout parameters
LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageSize, imageSize);
imageParams.setMargins(0, 0, imageMargin, 0);
imageParams.gravity = Gravity.CENTER_VERTICAL;
// setup image view
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageResId);
imageView.setLayoutParams(imageParams);
// modify root layout
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.addView(imageView, 0);
return toast;
}