Android的TextView如何设置首字母大写

1,056 阅读1分钟

这是很小的一个小需求,想了想觉得没那么简单,并没有现成的API供我们调用,自己写一个,记录下来供有类似需求的同行参考。

要让Android TextView中的文本首字母大写,可以使用TextWatcher来监听输入变化并自动转换。具体实现方式如下:

  1. 在xml文件中定义一个TextView,并设置android:inputType="textCapSentences",以启用句首字母大写的输入法类型。
<TextView
    android:id="@+id/myTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"
    android:inputType="textCapSentences" />

  1. 在Java代码中,定义一个TextWatcher对象,并实现其onTextChanged()方法,用于在文本变化时将首字母转换为大写。
final TextView textView = findViewById(R.id.myTextView);

// 定义TextWatcher
TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        // 将文本的首字母转换为大写
        String text = charSequence.toString();
        if (!TextUtils.isEmpty(text)) {
            text = text.substring(0, 1).toUpperCase() + text.substring(1);
            textView.setText(text);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }
};

// 添加TextWatcher
textView.addTextChangedListener(textWatcher);

这样,在输入文本时,每次输入完一个单词后,TextView中的文本就会自动将该单词的首字母转换为大写。