.
106-Android Toast
A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.
Creating a simple Toast
1) Run ADT and open My First App project
Create a new project MyFirstApp.
or
Download MyFirstApp Project here:
2) Edit Resource Files
2.1) Strings
File: res/values/strings.xml
| 
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="app_name">My First App</string> 
    <string name="edit_message">Enter a message</string> 
    <string name="button_send">Send</string> 
    <string name="action_settings">Settings</string> 
    <string name="title_activity_main">MainActivity</string> 
    <string name="menu_settings">Settings</string> 
</resources> | 
2.2) Layout
File: res/values/activity_main.xml
| 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    tools:context=".MainActivity" > 
    <EditText 
        android:layout_weight="1" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:hint="@string/edit_message" /> 
    <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@string/button_send" 
        android:onClick="sendMessage" /> 
</LinearLayout> | 
2) Edit MainActivity.java
File:MainActivity.java
| 
package com.example.myfirstapp; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Toast; 
public class MainActivity extends Activity { 
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
                super.onCreate(savedInstanceState); 
                setContentView(R.layout.activity_main); 
        } 
        @Override 
        public boolean onCreateOptionsMenu(Menu menu) { 
                // Inflate the menu; this adds items to the action bar if it is present. 
                getMenuInflater().inflate(R.menu.activity_main, menu); 
                return true; 
        } 
        public void sendMessage(View v){ 
                //display in long period of time 
                Toast.makeText(getApplicationContext(), "Send Message", Toast.LENGTH_LONG).show(); 
        } 
} | 
| 
If you want to display a short toast, change as follows 
Toast.makeText(getApplicationContext(), "Send Message", Toast.LENGTH_SHORT).show(); | 
OUTCOME.
 
No comments:
Post a Comment