我有一个工作正常的警告对话框,但我怀疑我可以清理一些代码。我使用stringBuilder
来帮助汇总消息,除了使用String.format来获取每行的空间。 String.format
阻止我像平常一样追加。我宁愿不使用四(4)个字符串对象来完成所有这些。给我一个更简洁的编码,永远保持冷静。
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("Total Counts");
StringBuilder stringBuilder = new StringBuilder();
String one= String.format("%-10s %s", calCount1, "#1 count\n");
String two= String.format("%-10s %s", calCount2, "#2 count\n");
String three= String.format("%-10s %s", calCount3, "#3 count\n");
String four= String.format("%-10s %s", calCount4, "#4 count\n");
stringBuilder.append(one);
stringBuilder.append(two);
stringBuilder.append(three);
stringBuilder.append(four);
builder.setMessage(stringBuilder.toString());
...
答案 0 :(得分:1)
也许这就是。
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("Total Counts");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("%-10s %s", calCount1, "#1 count\n"));
stringBuilder.append(String.format("%-10s %s", calCount2, "#2 count\n"));
stringBuilder.append(String.format("%-10s %s", calCount3, "#3 count\n"));
stringBuilder.append(String.format("%-10s %s", calCount4, "#4 count\n"));
builder.setMessage(stringBuilder.toString());
答案 1 :(得分:0)
您可以在字符串资源中使用格式化占位符。请参阅"格式化字符串"部分下的this page。它应该像您一样使用标准格式修饰符。