Thursday, 16 March 2017

Customizing Toast in Android

This post is regarding the customization of a Toast in your application.
You may have seen many a times some toast messages in android application notifying you that something has been completed or some action has been performed or executed.
These toast messages that you see are of the default representation from android but you can also customize your toast as you want.
This is quite simple which can be implemented as follows:

1. Create your xml layout file (custom_toast.xml) to show how your toast will look like.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="16dp"
            android:src="@drawable/sample_image" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="16dp"
            android:lines="2"
            android:text="This is your custom toast..!!!"
            android:textAlignment="center"
            android:textSize="12dp" />

    </LinearLayout>
</LinearLayout>

2. In your activity where you want to show the toast, just add the following snippet.

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.custom_toast, null);
        Toast toast = new Toast(this);
        toast.setView(layout);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.show();

That's all. Here you go.
Share and comment if any issues.



No comments:

Post a Comment