0

How can I change the background color of a Toast in a Xamarin Forms Application?

I've tried this code on Android 11:

Context context = Android.App.Application.Context;
string message = "Hello toast!";
ToastLength duration = ToastLength.Short;

Toast t = Toast.MakeText(context, message, duration);
System.Drawing.Color c = Xamarin.Forms.Color.Green;
ColorMatrixColorFilter CM = new ColorMatrixColorFilter(new float[]
{
    0,0,0,0,c.R,
    0,0,0,0,c.G,
    0,0,0,0,c.B,
    0,0,0,1,0            
});
t.View.Background.SetColorFilter(CM);
t.Show();

But I get the following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

RobC
  • 22,977
  • 20
  • 73
  • 80
  • 1
    which **specific** line throws the exception? At a glance it doesn't even seem like that code should compile. – Jason May 16 '22 at 20:54
  • 1
    this has also been asked numerous times: https://www.google.com/search?q=android+toast+background+color+site:stackoverflow.com – Jason May 16 '22 at 20:55

1 Answers1

0

The custom toast views are deprecated since Android 11. So the value of t.View in your code is null.

Just like the official document says:

Custom toast views are deprecated. Apps can create a standard text toast with the makeText(android.content.Context, java.lang.CharSequence, int)

You can check the following case:Toast.getView() returns null on Android 11 (API 30)

Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14