There is always the opportunity to create your own layout. There was one fact that I did not like: it violates the default toast user interface. This may vary across platforms and implementations. There is no easy way to use the default system resource, so I decided to crack the toast and paste the image into it.
Hint: you can get the default resource as follows: Toast.makeToast(context, "", 0).getView().getBackground()
Here's the helper that will display the image before the toast: Helper.makeImageToast(context, R.drawable.my_image, "Toast with image", Toast.LENGTH_SHORT).show()
I use this to indicate success, information or error. Makes the toast information more beautiful and expressive ...
(It’s worth mentioning that the hack is based on the fact that the internal toast uses LinearLayout , therefore it does not depend on the system and implementation. 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; }
Knickedi Oct 24 2018-11-21T00: 00Z
source share