Android:setText销毁格式化的字符串

时间:2014-03-19 02:20:16

标签: android string-formatting android-view settext text-formatting

我是Android编程的新手,我正在开发一个财务管理应用程序。目前我遇到一个问题,即setText()方法破坏了我传入的字符串格式。

我有一个Account类,它有一个习惯的toString方法,它返回一个格式化的帐户信息字符串:

public String toString(int colWidth1, int colWidth2, int colWidth3) {
    return String.format("%-" + colWidth1 + "s", myDisplayName) +
            String.format("%-" + colWidth2 + "s", myBalance) + 
            String.format("%-" + colWidth3 + "s", myInterestRate);
}

在AccountInfo活动中,我有:

// create a table that contains all account information of the current user
    TableLayout accountTable = (TableLayout) findViewById(R.id.tableLayout_account_details);
    List<Account> accountList = accountManager.getAllAccounts(CurrentUser.getCurrentUser().getUserName());

    // for each account, display name, balance and interest rate
    for (int i = 0; i < accountList.size(); i++) {
        Account account = accountList.get(i);
        TableRow accEntry = new TableRow(this);
        Button accButton = new Button(this);
        accButton.setText(account.toString(10, 10, 10));
        Log.i("account info", account.toString(10, 10, 10));

        // button format
        TableRow.LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(0, -7, 0, -10);
        accButton.setLayoutParams(params);
        accButton.setGravity(Gravity.LEFT);

        // add button to the row
        accEntry.addView(accButton);

        // add row to the table
        accountTable.addView(accEntry);

        // ...more code here for button click listener
    }

虽然我的logcat打印出了我想要的格式很好的字符串,但是按钮上的文字没有很好地排列

(刚才意识到我没有足够的声誉来发布我的应用的截图...)

我已经尝试了很长时间的调试,但仍然没有线索。任何帮助都非常感谢!!!

编辑:截图

  

enter image description here

2 个答案:

答案 0 :(得分:1)

我的室友指出了问题!他很棒!!!

对齐关闭,因为字体不是等宽字体。只需做

android:typeface="monospace"

在布局xml中解决问题!!!

答案 1 :(得分:0)

我想从Android Studio回答:

不要连接用setText显示的文本。将资源字符串与占位符一起使用。

调用TextView#setText:

永远不要调用Number#toString()来格式化数字;它不会正确处理分数分隔符和特定于语言环境的数字。请考虑使用具有正确格式规范(%d或%f)的String#格式。

不要传递字符串文字(例如&#34; Hello&#34;)来显示文字。硬编码文本无法正确翻译为其他语言。请考虑使用Android资源字符串。

不要通过连接文本块来构建消息。此类消息无法正确翻译。