
Post by: Priyanshu Kumar Chaudhary
A toast is small message displayed on the top of the content of our activity. By default, toast are displayed on the bottom of the activity.
Code for Default Toast:-
1 |
Toast.makeText(getApplicationContext(),"Hi, We are Andro Indian",Toast.LENGTH_SHORT).show(); |
Here, the static makeText() method of Toast Class takes 3 arguments as input.
- Context context,
- CharSequence text or @StringRes int ResId
- @IntDef int duration
You can either show toast for short duration or long duration.
a] Toast.LENGTH_SHORT is used to display toast for about 2 seconds.
b] Toast.LENGTH_LONG is used to display toast for about 4 to 5 seconds.
Preview of Default Toast:-
In general, any popular apps do not use the default toast. They create their own custom toast & display it to users as per their requirement.
Steps for making Custom Toast:-
Step 1:- Create a layout named “custom.xml” with root ViewGroup id as “customid”.
Custom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@color/colorAccent" android:id="@+id/customid" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hi, We are Andro Indian"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="And, You are seeing custom Toast"/> </LinearLayout> |
Step 2:- Make a applyCustomToast()
1 2 3 4 5 6 7 8 9 10 11 12 |
private void applyCustomToast() { Toast toast=new Toast(getApplicationContext()); LayoutInflater layoutInflater=getLayoutInflater(); View view=layoutInflater.inflate(R.layout.custom,(ViewGroup)findViewById(R.id.customid)); toast.setView(view); // set the view to the toast object toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER,0,0); // setGravity method takes three arguments int gravity, int xOffSet, int yOffSet toast.show(); } |
Step 3:- Call the applyCustomToast() as per your requirement.
applyCustomToast();
Output;