Android: How to set the colour of a Toast's text

Viewed 71956

I am displaying a toast message as the result of an if statement using the following code:

Toast.makeText(getBaseContext(), "Please Enter Price", Toast.LENGTH_SHORT).show();

It is displayed as white text on a white background, as such it can not be read! My question is, how can I change the colour of the toast's text?

10 Answers

You can try this if you don't wish to use any custom libraries

 Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
        View view=toast.getView();
        TextView  view1=(TextView)view.findViewById(android.R.id.message);
        view1.setTextColor(Color.YELLOW);
        view.setBackgroundResource(R.color.colorPrimary);
        toast.show();

Here is an example in Kotlin, showing how you can change the background color of a toast and it's text color :

val toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
toast.view.background.setColorFilter(ContextCompat.getColor(context, 
R.color.white), PorterDuff.Mode.SRC_IN)
val textView = toast.view.findViewById(android.R.id.message) as TextView
textView.setTextColor(ContextCompat.getColor(context, R.color.black))
toast.show()

The solution with setting a custom view on Toast is deprecated for API 30 and forward.

Documentation says

apps * targeting API level {@link Build.VERSION_CODES#R} or higher that are in the background * will not have custom toast views displayed.

The alternative is

Toast.makeText(applicationContext,
                HtmlCompat.fromHtml("<font color='red'>custom toast message</font>", HtmlCompat.FROM_HTML_MODE_LEGACY),
                Toast.LENGTH_LONG).show()

Html color tag can also be <font color='#ff6347'>

For every modification that has to do with the text displayed the above solution would be enough. You can for example make the text bold by inserting <b>my text</b> or you maybe want to change the font-familywith <font font-family='...'> my text </font> For all those changes that solution will be enough.

If you want to modify the container though with properties like background-color the only alternative is to use Snackbar. View can not be modified for Toast anymore.

Related