Wednesday, March 5, 2014

Android Toast Example With Source Code

In Android, Toast is a notification message that pop up, display a certain amount of time, and automtaically fades in and out, most people just use it for debugging purpose.
Code snippets to create a Toast message :
//display in short period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
 
//display in long period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();

1.  Toast View

Simple Toast example.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


<Button android:id="@+id/button1" android:layout_marginLeft="100dp" android:layout_marginTop="100dp" android:layout_height="wrap_content" android:text="Click Me" android:layout_width="wrap_content"></Button>
</LinearLayout>
File : MainActivity.java
package com.helloexample;




import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class HelloAndroidActivity extends Activity implements  OnClickListener{
 
 private Button btn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(this);
        
    }
    public void onClick(View v) {
  Intent i;
  switch (v.getId()) {
  case R.id.button1:
   Toast.makeText(getApplicationContext(), "Hello Android", Toast.LENGTH_LONG).show();
   
   
   break;
  
  default:
   break;
  }
 }

}
See demo, when a button is clicked, display a  Toast message

1 comment: