Toast in Android
Android Toast is used to show sort message. Toast message takes only that amount of space that is required to show message, and during that time activity is visible and user can interact with it.
Toasts automatically disappear after a timeout.
Toast Usage :
We can use Toast to show sort message as follows:
Toast.makeText( getApplicationContext(), "Your Message", Toast.LENGTH_LONG ).show();
|
We need to pass 3 arguments in Toast.makeText(Context context,String message,int length) function as follows:
- Context: First argument is Context object
- String: Message which you want to display in Toast.
- int: third parameter is duration. It can have values Toast.LENGTH_SHORT or Toast.LENGTH_LONG
We can change the position of Toast with the setGravity(int, int, int) method of Toast object. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
For example, To position Toast in the center of screen, we can set the gravity like this:
Toast toast = Toast.makeText(getApplicationContext(), "Your Message", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Create Project :
a) Open Android Studio
b) Go to File >New> New Project > Project Name > Next > Next > Next > Finish
Layout Design :
open activity_main.xml file and replace the given bellow code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4286f4"
android:orientation="vertical"
tools:context="app.aion.DemoActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Apna Java"
android:textColor="#41f4ca"
android:textSize="20dp" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast Example" />
</LinearLayout>
Code:
Open MainActivity.java file and replace the given bellow code.
package app.apnajava;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnToast;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnToast=(Button)findViewById(R.id.btn);
btnToast.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText( getApplicationContext(), "Hi... This is Apna Java Toast Tutorial.", Toast.LENGTH_LONG ).show();
}
});
}
}
Comments
Post a Comment