Displaying A Toast Message With Image

This example shows how to display toast message with image in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it ToastWithImageExample.

2.) Write following into main.xml:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ToastWithImageExampleActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>

 

3.) Run for output.

Steps:

1.) Create a project named ToastWithImageExample and set the information as stated in the image.

Build Target: Android 4.4
Application Name: ToastWithImageExample
Package Name: com.example.ToastWithImageExample
Activity Name: ToastWithImageExampleActivity

ToastWithImageExample1

2.) Open ToastWithImageExampleActivity.java file and write following code there:

 

package com.example.toastwithimageexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ToastWithImageExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Toast ImageToast = new Toast(getBaseContext());
LinearLayout toastLayout = new LinearLayout(getBaseContext());
toastLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView image = new ImageView(getBaseContext());
TextView text = new TextView(getBaseContext());
image.setImageResource(R.drawable.ic_launcher);
text.setText("Hello!");
toastLayout.addView(image);
toastLayout.addView(text);
ImageToast.setView(toastLayout);
ImageToast.setDuration(Toast.LENGTH_LONG);
ImageToast.show();
}
}

 

3.) Compile and build the project.

Output

ToastWithImageExample2