3

I am trying to format the text on an Android TextView. This is the code I tried in a Java console:

System.out.println(String.format("%-7s 56", "S"));
System.out.println(String.format("%-7s 56", "A(102)"));

The output is the expected, my text is left aligned:

S       56
A(102)  56

No I try the same code on Android TextView:

mTextView.setText(String.format("%-7s 56\n", "S"));
mTextView.append(String.format("%-7s 56", "A(102)"));

And this is the result:

enter image description here

As you can see the output is not the expected the text is not aligned. What I am doing wrong? Is there any other way to do this?

4

2 回答 2

10

问题是我没有使用等宽字体。

等宽字体,也称为固定间距、固定宽度或非比例字体,是一种字体,其字母和字符各自占据相同数量的水平空间

所以我只在写入 TextView 之前添加了这一行:

mTextView.setTypeface(Typeface.MONOSPACE);
于 2013-09-07T23:35:40.630 回答
0
// I Think You Have To Achieve this in this way

// XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp" >

        <TextView
            android:id="@+id/txtCal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtCalValue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>

// Activity
    TextView txtCal;
    TextView txtCalValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtCal = (TextView) findViewById(R.id.txtCal);
        txtCalValue = (TextView) findViewById(R.id.txtCalValue);

        txtCal.setText("S\nA(102)");
        txtCalValue.setText("56\n56");

    }
于 2013-09-10T04:35:49.267 回答