Android Custom Toast

Android Custom Toast Example

MainCLASS

package com.example.malik.javatpoint;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Creating the LayoutInflater instance
LayoutInflater li = getLayoutInflater();
//Getting the View object as defined in the customtoast.xml file
View layout = li.inflate(R.layout.customtoast, (ViewGroup) findViewById(R.id.custom_toast_layout));

//Creating the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);//setting the view of custom toast layout
toast.show();
}
}

MainXML

<?xml version=”1.0″ encoding=”utf-8″?>
<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=”com.example.malik.javatpoint.MainActivity”
android:background=”#c70a0a”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceMedium”
android:text=”Hello World”
android:id=”@+id/textView”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”73dp” />
</RelativeLayout>

 

customtoast XML

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical” android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/custom_toast_layout”
>

<ImageView
android:id=”@+id/custom_toast_image”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:contentDescription=”hello_world”
android:src=”@drawable/pic4″
android:gravity=”center”/>

<TextView
android:id=”@+id/custom_toast_message”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:contentDescription=”Toast”
android:layout_gravity=”center”
android:textSize=”29dp”
android:text=”Welcome Malik Himani” />

</LinearLayout>

Output :

pic

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.