We use toast to display a small popup, which contains messages or information. It used to give feedback to a user regarding any operation.
For example, when you set alarm you receive a feedback of “Alarm will ring in 16 minutes.” written in the form of toast message.
Let’s first see its features,
- It will disappear automatically after a timeout.
- It only fills the amount of space required for the message or information.
- Toasts are not clickable.
- The current activity remains visible and interactive.
Syntax
Toast.makeText(Context c, CharSequence text, int duration).show();
The Toast.makeText()
method creates a Toast object.The method takes 3 parameters.
- Context: First the method needs a Context which is obtained by calling MainActivity.this (or getApplicationContext() , for fragment use getcontext()).
- Text: The second parameter is the text to be displayed in the toast.
- Duration: The third parameter is the time duration the toast is to be displayed. The toast class contains two predefined constants you can use:
- Toast.LENGTH_SHORT -> Display the toast for 2000ms(2 sec)
- Toast.LENGTH_LONG -> Display the toast for 3500ms(3.5 sec)
.show()
: This method shows the Toast.
Let’s Create a Toast
Step 1: Enabled view binding in build.gradle(Module:app)(Since we are using view binding instead of findviewById)
// Available in Android Gradle Plugin 3.6.0
android {
viewBinding{
enabled=true
}
}
In Android Studio 4.0, viewBinding
has been moved into buildFeatures
and you should use:
// Android Studio 4.0
android {
buildFeatures {
viewBinding = true
}
}
Step 2: Just add the Button in the XML File.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast" />
Step 3: MainActivity.java
View binding generates a binding object for every layout in our module.(activity_main.xml) —> (ActivityMainBinding.java)
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);//here button is our id.
binding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showToast("Hello World!");
}
});
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
View binding gives you the ability to replace findViewById with generated binding objects to simplify code.
This is how our simple toast look
Hope this helped, thank you for reading the post ❤