Home > database >  Xamarin Toast.MakeText change Color
Xamarin Toast.MakeText change Color

Time:05-17

how can I change the backgroundcolor 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.'

CodePudding user response:

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)

  • Related