Search code examples
androidviewnullbackgroundtoast

How to customize Toast background color when toast.view.background is null?


Setting a color filter on the Toast's view's background seemed like the best approach. But toast.view.background is null so I get an NPE and the setColorFilter() method fails.

fun showToast(context: Context, text: String) {
    val toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)

    // customize background color
    toast.view.background.setColorFilter(
        ContextCompat.getColor(context, R.color.toast_background),
        PorterDuff.Mode.SRC_IN
    )
    toast.show()
}

I also tried creating a custom drawable and setting toast.view.background to the drawable, but it shows my custom drawable behind the default Toast background.

view.background = ContextCompat.getDrawable(context, R.drawable.toast_background)

enter image description here


Solution

  • You can create custom layout file and inflate from that. This will give you flexibility on setting background and adding more widgets to view. In following sample, I set background color to red and text color to white but you can customize according to your needs.

    1. Create toast_with_custom_view layout file and add following:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white" />
    </LinearLayout>
    
    1. Inflate custom view using following code:
    private fun showToast() {
        // inflate the custom layout
        val toastView = layoutInflater.inflate(R.layout.toast_with_custom_view, null)
        toastView.findViewById<TextView>(R.id.textView).text = "Hello, world!"
    
        val toast = Toast(applicationContext)
        // set custom view
        toast.view = toastView
        toast.show()
    }