在Android布局xml文件中大写TextView的第一个字母

qwe*_*guy 3 android capitalize textview

我在布局xml文件中有一个TextView,如下所示:

<TextView
   android:id="@+id/viewId"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/string_id" />
Run Code Online (Sandbox Code Playgroud)

我的字符串是这样指定的:

<string name="string_id">text</string>
Run Code Online (Sandbox Code Playgroud)

没有java代码,是否可以使其显示"Text"而不是"text" ?
(并且不改变字符串本身)

Hyr*_*mon 6

不.但是你可以创建一个简单的CustomView扩展TextView来覆盖setText并将第一个字母大写,就像Ahmad所说的那样,并在XML布局中使用它.

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class CapitalizedTextView extends TextView {

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text.length() > 0) {
            text = String.valueOf(text.charAt(0)).toUpperCase() + text.subSequence(1, text.length());
        }
        super.setText(text, type);
    }
}
Run Code Online (Sandbox Code Playgroud)