Displaying messages on the screen is one of the basic tasks when developing Android applications. Without this, it is impossible to interact with the user: confirm actions, show errors, or simply inform about processes. In Android Studio there is at least 5 standard methods display text - from simple notifications to full-fledged dialog boxes. But which method should you choose? It all depends on the context: whether feedback from the user is needed, how critical the message is and how long it should be visible.
Beginners often limit themselves Toast, not knowing what is more convenient for debugging Logcatand for important warnings โ AlertDialog. This article will analyze each method with code examples, implementation nuances and common errors. You will learn not only to display text, but also to do it effectively without interface delays and taking into account material design.
We will pay special attention to two aspects: performance (for example, why Toast.makeText() in a loop is a bad idea) and user experience (when is it better to use Snackbar instead of AlertDialog). At the end of the article there is a checklist for choosing the optimal method for displaying messages in your project.
1. Toast: simple pop-up notifications
Toast are the most popular way to show a short message that disappears after 2-3 seconds. It is often used to confirm actions (for example, "File saved") or non-critical errors ("No Internet connection").
Basic syntax:
Toast.makeText(context, "Message text", Toast.LENGTH_SHORT).show();
Where context is the context of the activity or application (usually this or getApplicationContext()), and LENGTH_SHORT (2 sec) or LENGTH_LONG (3.5 sec) set the display duration.
โ ๏ธ Attention: Do not overuse Toast in cycles or frequent events (for example, in onScroll). Each call creates a new object, which can lead to lags. For debugging, it is better to use Logcat.
- โ Pros: Simplicity, does not require markup, works without permission.
- โ Cons: You cannot add buttons or customize the design (without crutches).
- ๐ง Nuance: In new versions of Android, Toast may not be shown on top of system dialogs.
Example with customization (changing position and style):
Toast toast = Toast.makeText(context, "Custom Toast", Toast.LENGTH_LONG);toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 100);
toast.getView().setBackgroundColor(Color.BLUE);
toast.show();
2. Logcat: outputting messages for debugging
Logcat is a tool for outputting service messages to the console Android Studio. It is not visible to the user, but is essential for debugging. Use it to check the values โโof variables, monitor the execution of methods, or catch errors.
Main class methods Log:
Log.d("TAG", "Debug message"); // DebugLog.i("TAG", "Information message"); // Info
Log.w("TAG", "Warning"); // Warning
Log.e("TAG", "Error", exception); // Error
Where "TAG" is a unique identifier (usually a class name), and the message may contain variables:
Log.d("MainActivity", "Counter value: " + counter);
โ ๏ธ Attention: Do not leave Log in release version! They slow things down and can reveal sensitive information. Delete them before publishing or use BuildConfig.DEBUG:
if (BuildConfig.DEBUG) {Log.d("TAG", "Only the developer will see this message");
}
- ๐ Tip: In Logcat you can filter messages by
TAGor severity level (Error, Warning etc.). - ๐ฑ Tip: On some devices (for example, Xiaomi) Logcat may be limited by default.
Use a plugin Android Logcat Viewer for convenient viewing of logs directly in the code editor.
3. TextView: static and dynamic text
TextView is a standard interface element for displaying text. Unlike Toast, it remains on the screen until code changes it or the user closes the activity.
To display text in TextView, first add it to the markup (activity_main.xml):
<TextViewandroid:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, world!" />
Then get a link to it in the code and change the text:
TextView textView = findViewById(R.id.myTextView);
textView.setText("New text");
To dynamically update (for example, a counter) use:
textView.setText(String.format("Score: %d", score));
| Method | Description | Example |
|---|---|---|
setText() |
Sets text | textView.setText("Hello") |
append() |
Adds text to the end | textView.append("\nAdded") |
setTextColor() |
Changes text color | textView.setTextColor(Color.RED) |
setVisibility() |
Hide/show text | textView.setVisibility(View.GONE) |
โ ๏ธ Attention: Avoid frequent updates TextView in the main thread (for example, in a loop). This blocks the interface. For heavy operations, use Handler or RxJava.
How to update a TextView from a background thread?
Use runOnUiThread():
runOnUiThread(new Runnable() {@Override
public void run() {
textView.setText("Updated from a background thread flow");
}
});
Or View.post():
textView.post(() -> textView.setText("New text"));
4. AlertDialog: dialog boxes with buttons
AlertDialog is a modal window that requires user reaction. It blocks interaction with the interface until the user clicks a button (for example, "OK" or "Cancel").
Simple dialogue with one button:
new AlertDialog.Builder(this).setTitle("Attention")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", (dialog, which) -> finish())
.setNegativeButton("No", null)
.show();
For customization (for example, adding an icon or several buttons) use:
AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.ic_warning);
builder.setTitle("Warning");
builder.setMessage("Data not saved. Close without saving?");
builder.setPositiveButton("Save", (dialog, which) -> saveData());
builder.setNegativeButton("Do not save", (dialog, which) -> finish());
builder.setNeutralButton("Cancel", null);
builder.show();
- ๐จ Design: In new versions of Android, use
MaterialAlertDialogBuilderto match Material Design. - โ ๏ธ Error: Do not create dialogs in
onCreate()without verificationisFinishing()- this may cause leakage memory. - ๐ Alternative: For non-blocking notifications, use
Snackbar.
The dialog is not shown in onPause()|Checked isFinishing()|The text of the buttons is clear to the user|Added processing presses-->
5. Snackbar: The modern replacement for Toast
Snackbar is an improved version of Toastthat appears at the bottom of the screen and supports actions (like the Cancel button). It is included in the library Material Components and is recommended by Google for short notifications.
Basic example:
Snackbar.make(view, "File deleted", Snackbar.LENGTH_LONG).setAction("Cancel", v -> restoreFile())
.show();
Where view is the root element of the markup (usually findViewById(android.R.id.content)).
Customization Snackbar:
Snackbar snackbar = Snackbar.make(view, "No connection", Snackbar.LENGTH_INDEFINITE);snackbar.setAction("Repeat", v -> retryConnection());
snackbar.setActionTextColor(Color.YELLOW);
snackbar.setBackgroundTint(Color.RED);
snackbar.show();
โ ๏ธ Attention: Snackbar automatically adapts under a dark theme, but in manual customization of colors (for example, setBackgroundTint) this behavior may break. Always test on different topics.
- โจ Advantages:
- Supports actions (buttons).
- Can display for an unlimited time (
LENGTH_INDEFINITE). - Looks better on modern devices.
- ๐ Disadvantages:
- Requires a dependency
com.google.android.material:material. - Does not work without
View(unlikeToast).
- Requires a dependency
Snackbar is the best choice for notifications with an action (for example, "Undo deletion").
Comparison of methods: which one to choose?
The choice of message display method depends on goals, context and importance information. Below is a comparative table:
| Method | Visibility to the user | Interaction | When to use |
|---|---|---|---|
Toast |
Yes, disappears after 2-3 seconds | No | Brief confirmations ("Saved") |
Logcat |
No (only for developer) | No | Debugging, error logging |
TextView |
Yes, constantly | No (unless added) | Static text, counters, event log |
AlertDialog |
Yes, locks the screen | Yes (buttons) | Important questions ("Delete the file?") |
Snackbar |
Yes, disappears or by action | Yes (optional) | Notifications with an option ("Cancel") |
๐น Selection rule:
- Is interaction necessary? โ
AlertDialogorSnackbar. - Is the message temporary? โ
ToastorSnackbar. - Do I need to log data? โ
Logcat. - Should the text remain on the screen? โ
TextView.
Typical mistakes and how to avoid them
Even experienced developers sometimes make mistakes when displaying messages. Here are the most common problems and their solutions:
-
Toast is not shown.
๐น Reason: Called from a background thread or incorrect
context(for example,getApplicationContext()insteadActivity).๐น Solution: Use
runOnUiThreador the correct context:runOnUiThread(() -> Toast.makeText(MainActivity.this, "Text", Toast.LENGTH_SHORT).show()); -
AlertDialog causes a memory leak.
๐น Cause: Creating a dialog in
onCreate()without checkingisFinishing().๐น Solution: Check the activity status:
if (!isFinishing()) {new AlertDialog.Builder(this).show();
} -
Snackbar is not displayed.
๐น Reason: Incorrect binding to
View(for example, usingnullor invisible element).๐น Solution: Bind to root view:
Snackbar.make(findViewById(android.R.id.content), "Text", Snackbar.LENGTH_LONG).show();
โ ๏ธ Attention: On some devices (for example Huawei or Xiaomi) system dialogs may overlap your Toast or Snackbar. Test on different firmware!
FAQ: Frequently asked questions
Is it possible to show Toast in the Background Service?
No, Toast required Context bound to the UI thread. In the service, use Handler:
new Handler(Looper.getMainLooper()).post(() ->Toast.makeText(getApplicationContext(), "Text", Toast.LENGTH_SHORT).show()
);
Or send an event to Activity via BroadcastReceiver.
How to make multiple Toast without delays?
By default Toast ignores repeated calls with the same text. To show a duplicate, create a new object:
Toast currentToast = Toast.makeText(context, "Text", Toast.LENGTH_SHORT);currentToast.show();
// When shown again:
currentToast.cancel(); // Hide the previous one
currentToast = Toast.makeText(context, "Text", Toast.LENGTH_SHORT);
currentToast.show();
Why is Snackbar better than Toast?
Snackbar Supports:
- Action buttons (for example, "Cancel").
- Animation of appearance/disappearance.
- Adaptation to a dark theme.
- Display on top of other elements (for example,
BottomNavigationView).
Toast simpler, but inferior in functionality.
How to display rich text in AlertDialog?
Use SpannableString:
SpannableString spannable = new SpannableString("Important text");spannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
new AlertDialog.Builder(this)
.setMessage(spannable)
.show();
Why is TextView not updating in real time?
You are probably updating it not on the main thread. Use:
textView.post(() -> textView.setText("New text"));
Or for cyclic updates (for example, a timer) use Handler:
final Handler handler = new Handler(Looper.getMainLooper());handler.post(new Runnable() {
@Override
public void run() {
textView.setText("Updated: " + System.currentTimeMillis());
handler.postDelayed(this, 1000); // Repeat every second
}
});