Damon: BY - JANUARY 18, 2010
Damon: BY - JANUARY 18, 2010
To celebrate my new purchase for a Google Nexus One Ive started looking into Android
development.
Android is built in Java and since I studied Java at University I decided to have a little play.
From experience of using Android there are times when on screen messages pop up for
whatever reason. In Android these are called Toast.
Ive included a full class which explains how these Toast Objects are created. If youre just
interested in getting a Toast message to appear then the following code will work for you.
// Create a piece of toast.
Toast pieceToast = Toast.makeText(getApplicationContext(), toastText.getText(),
Toast.LENGTH_SHORT);
The following class is a complete application albeit a very small one. Its purpose is to display
a text field which allows the user to enter text and button which will show a Toast message.
/**
* This is a Android example to which shows how to display a piece of toast.
* Makes use of OnClickListener interface
*
* @author Damon Skelhorn
*/
package com.damon86.toastExample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create textfield
toastText = new EditText(getApplicationContext());
toastText.setText("Hello Toast!");
/**
* Implemented method - onClick.
* Show the user a piece of toast.
*/
@Override
public void onClick(View v) {
The class implements the OnClickListener Interface. For those who do not know what an
interface is, its a absract type which contains a set of empty methods know as method
signatures. When a class implements a interface, Java expects your class to contain these
methods. You can then write any code within these methods.
To make sure the button executes the code contained in the onClick method, the
onClickListener is set on the button by using the following code;
showToast.setOnClickListener(this);