A toast displays a simple message in a small popup, which automatically disappear after a timeout. The code to display a Toast is:
Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();
Position of Toast: A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset. For example, if you decide that the toast should appear in the top-right corner, you can set the gravity like this:
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
Now let’s create an app which Toast a message on button click.
Step 1: Create a new project and name it toastexample. Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a Button in a LinearLayout.
<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:padding="10dp" tools:context=".MainActivity"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="#f00" android:padding="10dp" android:text="Show Toast" android:textColor="#fff" android:textStyle="bold" /> </LinearLayout>
Step 3: Open app -> java -> package and open MainActivity.java. Add following code in it. Here we will Toast a message “This is my toast” when the user clicks the Button.
package example.myandroid.toastexample; import android.graphics.Color; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { //Declare Button private Button button1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Find Button using it's id from xml file button1 = (Button) findViewById(R.id.button1); //Set an onClickListener for the Button button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Toast a message when Button is clicked Toast.makeText(getApplicationContext(),"This is my toast", Toast.LENGTH_SHORT).show(); } }); } }
Output:
Now run the app and click on the button. The app will show toast message “This is my toast”.