当文本源自strings.xml时,我如何在Android Java中设置文本样式



我试图在AlertDialog中放入一条多段消息,并且在三段(短(之间有空行。当字符串在我的Java代码中编写时,它工作得很好,但当字符串源自字符串.xml时,它却失败得很惨。当文本来自字符串.xml时我有什么不同的做法?

请注意,我的strings.xml中message999的值正是我的Java代码中注释掉的消息变量中的值。

这是我的密码。

private void displayEmptySetMessage() {
Toast.makeText(this, getString(R.string.message999), Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(ListSales.this);
//Set the message.
//String message = "<p>There are currently no sales in the table.</p><br><p>If this is normal - you may have deleted all of your sales - and you wish to add rows with the add feature, please press Proceed.</p><br><p>If you think something is wrong, press Exit and contact your system administrator.</p>";
String message = getString(R.string.message999);
CharSequence styledMessage  = Html.fromHtml(message, Html.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL);
builder.setMessage(styledMessage);
//Set the title.
builder.setTitle("No Sales");
//Add the buttons
builder.setNegativeButton(R.string.proceed, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked Proceed button - do nothing except dismiss the dialog
}
});
builder.setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//User clicked Exit button - notify the system administrator and exit the app
Toast.makeText(ListSales.this, R.string.message009, Toast.LENGTH_LONG).show(); //placeholder
java.lang.System.exit(0);
}
});

//Create and display the AlertDialog
AlertDialog dialog = builder.create();
dialog.show();
}

如果注释掉的字符串足以满足您的需求,那么有几种简单的方法可以生成它(无需html格式(。

您可以在strings.xml文件中包括换行符,如

<string name="mymessage">This is paragraph 1.nnnThis is paragraph 2.nnnThis is the last paragraph.</string>

或者可以将XML文件中的段落分开

<string name="message_par1">This is paragraph 1.</string>
<string name="message_par2">This is paragraph 1.</string>
<string name="message_par3">This is the last paragraph.</string>

并在您的代码中组装完整的消息

String message = getString(R.string.message_par1) + "nnn" +
getString(R.string.message_par2) + "nnn" +
getString(R.string.message_par3);
builder.setMessage(message);

这不允许你进行任何html格式设置,但如果你只是试图模仿你注释掉的字符串,这应该会起作用。

也许您可以创建这样的消息。

String message = "Paragraph1" + "nnn" +
"Paragraph 2" + "nnn" + 
"Paragraph 3"
builder.setMessage(message);

最新更新