I need to display multiple lines of text in an Alert Dialog. If I use multiple setMessage() methods, only the last setMessage is displayed, as shown below.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Statistics:"); alertDialog.setMessage("No. of attempts: " + counter); alertDialog.setMessage("No. of wins: " + counterpos); alertDialog.setMessage("No. of losses: " + counterneg);
Is there a way to create a new line for each of these in the dialog? Like using \n in System.print.out(); method.
Thanks!
Alert Dialog code has three methods: setTitle() method for displaying the Alert Dialog box Title. setMessage() method for displaying the message. setIcon() method is use to set the icon on Alert dialog box.
The way to make a checkbox list is to use setMultiChoiceItems . // setup the alert builder AlertDialog. Builder builder = new AlertDialog. Builder(context); builder.
setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog. The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.
There are three kinds of lists available with the AlertDialog APIs: A traditional single-choice list. A persistent single-choice list (radio buttons) A persistent multiple-choice list (checkboxes)
You can do something like this
String alert1 = "No. of attempts: " + counter; String alert2 = "No. of wins: " + counterpos; String alert3 = "No. of losses: " + counterneg; alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3);
You could just create one string of everything you want to show and add "\n" where you'd like the line breaks to be.
alertDialog.setMessage("No. of attempts: " + counter + "\n" + "No. of wins: " + counterpos + "\n" + "No. of losses: " + counterneg);
Or even better to use a StringBuilder:
StringBuilder sb = new StringBuilder(); sb.append("No. of attempts: " + counter); sb.append("\n"); sb.append("No. of wins: " + counterpos); sb.append("\n"); sb.append("No. of losses: " + counterneg); alertDialog.setMessage(sb.toString());
And the best way to do it would be to extract the static texts into a string resource (in the strings.xml file). Use the %d (or %s if you want to insert strings rather than ints) to get the dynamic values in the right places:
<string name="alert_message">No. of attempts: %1$d\nNo. of wins: %2$d\nNo. of losses: %3$d</string>
And then in code:
String message = getString(R.string.alert_message, counter, counterpos, counterneg); alertDialog.setMessage(message);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With