Thursday, 5 September 2013

Custom Toast Demo

Demo:

1) MainActivity.java:
 
package com.venky.customtoastdemo; 
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

       Button btn;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);

             btn = (Button) findViewById(R.id.button1);
             btn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                           Toast toast = new Toast(MainActivity.this);
                           View view = getLayoutInflater().from(MainActivity.this)
                                        .inflate(R.layout.style, null);
                           toast.setGravity(Gravity.BOTTOM, 5, 5);
                           toast.setDuration(Toast.LENGTH_LONG);
                           toast.setView(view);
                           toast.show();
                    }
             });
       }
}

2) activity_main.xml: 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5F04B4"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="150dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:background="#ffffff"
        android:text="Show Toast"
        android:textColor="#000000"
        android:textSize="17dp" />

</LinearLayout>


3) style xml for Toast:  
<?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:background="#ffffff"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="This is Custom Toast message  "
            android:textColor="#5F04B4"
            android:textSize="17dp"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

4) Download this Project Click Here

No comments:

Post a Comment