Saturday, 22 June 2013

Dialog as Toast message in Android


What is toast message?

         In Adnroid, Toast is a notification message that pop up and display a cirtain amount of time.

What is drawback toast message?

         Toast message should displayed cirtain amount of time. We can not interrupt it within the time. For example if we set a toast message to display five seconds, we can not hide it within two or three seconds. Tha is main drawback of Toast message.

How to avercome this drawback?

         We can use Dialog as toast message in android. There is two main advantages by using Dialog as Toast message.
        1. We can hide the Toast message any time by touching the screen.
        2. While dispaly Toast message the background will goes to dim. So user can read the toast message without interruption of other views.

DialogToast.java

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class CustomToast extends Dialog {
 public CustomToast(Context context, String text) {
  super(context);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  LayoutInflater inflater = (LayoutInflater) context
  .getSystemService(android.content.Context.
     LAYOUT_INFLATER_SERVICE);

  View layout = inflater.inflate(R.layout.toast, null);
  TextView tv = (TextView) layout.findViewById(R.id.toastText);
  tv.setText(text);  
  setContentView(layout);
  show();
  setCanceledOnTouchOutside(true);
  setCancelable(true);
  Window window = getWindow();
  window.setGravity(Gravity.BOTTOM);
  new Handler().postDelayed(new Runnable() {

   public void run() {
    dismiss();
   }
  }, 2500);
 }
}


toast.xml

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

    <TextView
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000" />

</LinearLayout>


How to call this Dialog as Toast message?
         Following will allow you to display the Dialog as Toast message.
new CustomToast(activity, "Custom Toast").show();

Sample code to calling this Dialog as Toast message.

DialogToastActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class DialogToastActivity extends Activity {
 
 Activity activity;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        activity = this;     
    }
    public void mButtonClick(View v){
     new CustomToast(activity, "Custom Toast").show();
    }
}

Screen shot.



Thank You