info@androidpaper.co.in

How to Customize Toast message Show in Kotlin

In Kotlin, you can customize the appearance and behavior of the toast message by creating a custom layout for the toast and using a Toast object with a custom view. Here's how you can customize the toast message in Kotlin:

Create a custom layout XML file for the toast message. You can define the layout and style of the toast message in this file. For example, you can create a layout file named custom_toast_layout.xml:

<!-- custom_toast_layout.xml -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/custom_toast_background"
    android:padding="16dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_custom_icon"
        android:layout_marginEnd="8dp"/>

    <TextView
        android:id="@+id/custom_toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:text="Custom Toast Message"/>

</LinearLayout>

Create a drawable resource file for the background of the custom toast. For example, create a file named custom_toast_background.xml in the res/drawable directory:

<!-- custom_toast_background.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="8dp" />
    <solid android:color="#80000000" />
</shape>

In your Kotlin code, use the LayoutInflater to inflate the custom layout and create a custom Toast with the custom view:

import android.content.Context
import android.view.LayoutInflater
import android.widget.Toast

fun showCustomToast(context: Context, message: String) {
    // Inflate the custom layout
    val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    val layout = inflater.inflate(R.layout.custom_toast_layout, null)

    // Set the custom message text
    val textView = layout.findViewById<TextView>(R.id.custom_toast_text)
    textView.text = message

    // Create the custom Toast
    val toast = Toast(context)
    toast.duration = Toast.LENGTH_SHORT
    toast.view = layout
    toast.show()
}

Now, whenever you want to show a customized toast message, you can call the showCustomToast() function:

showCustomToast(this, "This is a custom toast message!")

In this example, we created a custom toast layout with an image and a text view. You can modify the XML layout and drawable files to customize the appearance of your toast according to your preferences. Remember to replace 'this' with the appropriate context if you are calling the function from a different scope.