Search code examples
androidtoast

Toast.getView() returns null on Android 11 (API 30)


I just installed the Android R (API 30) image in my emulator to try my app, and it crashed when trying to set the Background color of a Toast.

    Toast toast = Toast.makeText(ctxt, msg, duration);
    View view = toast.getView();
    view.setBackgroundColor(0xFF303030);
    TextView tview = view.findViewById(android.R.id.message);
    tview.setTextColor(Color.WHITE);
    toast.show();

This is really strange as in Android Q (API 29) works perfectly.

My build.gradle updated for Android R (API 30)

    compileSdkVersion 30
    buildToolsVersion "30.0.1"

Is there a new way to do it??


Solution

  • Since Android 11, custom toasts/ toast modifications are deprecated, according to Google to "protect users". Hence why your app in Android 30 is not able to display custom toasts.

    From Android Developers documentation:

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