April 13, 2011

How To display a simple Toast Notificatin in Android

To create a simple Toast Notification instantiate a Toast object passing the context, the text and the duration to its makeText() method, then call the show() method. The duration can be : Toast.LENGTH_LONG or Toast.LENGTH_SHORT.
Example:
Context context = getApplicationContext();
CharSequence text = "Write the toast message here";
int duration = Toast.LENGTH_SHORT;
Toast toastNodification = Toast.makeText(context, text, duration);
toastNodification.show();

You can also use the short (chained) version :
Toast.makeText(getApplicationContext(), "short version", Toast.LENGTH_SHORT).show();

Don't forget to add imports:
import android.content.Context;
import android.widget.Toast;

The result:


Complete code :

main.java

package com.blog.simpletoastnotification;

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

public class main extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button simpleBtn = (Button) findViewById(R.id.button1);
  simpleBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Context context = getApplicationContext();
    CharSequence text = "Write the toast message here";
    int duration = Toast.LENGTH_SHORT;
    Toast toastNodification = Toast.makeText(context, text, duration);
    toastNodification.show();
    
    // short version
   // Toast.makeText(getApplicationContext(),
"short version Toast", Toast.LENGTH_SHORT).show();
   }
  });

 }
}

main.xml





1 comentarii:

Mobi People said...

Hi many thanks to the author helpful information for android application.

To get all the offshore Android apps development or the Android application development, you need to hire dedicated mobile apps developer programmer, through which you will be able to get the best mobile development services at the personal as well as corporate level.

Post a Comment