Sunday, 3 February 2013

Custom Toast Example in Android

activity_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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/toast_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click Here to Display Toast" />

</RelativeLayout>

custom_toast_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_linear_toast"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@android:color/black">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_2" />

    <TextView
        android:id="@+id/toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Layout as a Toast"

        android:textColor="@android:color/white"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


MainActivity.java

package com.rajeshvijayakumar.toast_example;

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

public class MainActivity extends Activity implements OnClickListener {

    private Button mToastButton;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToastButton = (Button) findViewById(R.id.toast_button);
        mToastButton.setOnClickListener(this);
       
    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.toast_button) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast_layout,
                    (ViewGroup) findViewById(R.id.custom_linear_toast));
          

         Toast toast = new Toast(getApplicationContext());
          toast.setGravity(Gravity.BOTTOM, 0, 0);
          toast.setDuration(Toast.LENGTH_LONG);
          toast.setView(layout);
          toast.show();
        }
    }
}

Output :








Source Code : Download this example Here









No comments:

Post a Comment