Michał Powłoka
Michał Powłoka

Reputation: 1511

Capitalize the first letter in Android TextView using XML

I read plenty questions about that, for example:

Still, I didn't find a way to just capitalize the first letter of TextView text using XML. So far it looks like it's impossible but it is hardly believable to me.

So, how to capitalize the first letter of Android TextView text using XML?

Upvotes: 2

Views: 354

Answers (2)

Iulian Popescu
Iulian Popescu

Reputation: 2643

I'm pretty sure that you can't achieve that behaviour using only XML files, but if you extend the TextView class to a custom one that capitalises the first letter, then you should be able to use only XML from this point on.

public class CapitalizeTextView extends TextView {
    // Create here constructors matching super

    @Override
    public void setText(CharSequence text, BufferType type) {
        StringBuilder builder = new StringBuilder(text);
        builder.setCharAt(0, Character.toUpperCase(builder.charAt(0)));
        super.setText(builder.toString(), type);
    }
}

From this point on, you only have to use CapitalizeTextView instead of TextView and the first letter will be capitalised. It works from XML or Java/Kotlin.

<mobile.com.capitalize.CapitalizeTextView
    ......
    android:text="not capital letter" />


textView.setText("not capital letter");

Upvotes: 2

vincrichaud
vincrichaud

Reputation: 2208

You can do it by setting the capitalize attribute.

From the doc

0 : Don't capitalize

1 : Capitalize first letter of sentences

2 : Capitalize first letter of words

3 : Capitalize everything

Upvotes: 0

Related Questions