Capitalize first letter of TextView in an Android layout xml file

不羁的心 提交于 2019-12-04 12:51:47

No. But you can create a simple CustomView extending TextView that overrides setText and capitalizes the first letter as Ahmad said like this and use it in your XML layouts.

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);
    }
}
Jonas Borggren

I used Hyrum Hammon's answer to manage to get all words capitalized.

public class CapitalizedTextView extends TextView {

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

    @Override
    public void setText( CharSequence c, BufferType type ) {

        /* Capitalize All Words */
        try {
            c = String.valueOf( c.charAt( 0 ) ).toUpperCase() + c.subSequence( 1, c.length() ).toString().toLowerCase();
            for ( int i = 0; i < c.length(); i++ ) {
                if ( String.valueOf( c.charAt( i ) ).contains( " " ) ) {
                    c = c.subSequence( 0, i + 1 ) + String.valueOf( c.charAt( i + 1 ) ).toUpperCase() + c.subSequence( i + 2, c.length() ).toString().toLowerCase();
                }
            }
        } catch ( Exception e ) {
            // String did not have more than + 2 characters after space.
        }
        super.setText( c, type );
    }

}

Try this code in the activity:

String userName = "name";
String cap = userName.substring(0, 1).toUpperCase() + userName.substring(1);

Hope this helps you.

As Kotlin extension function

 fun String.capitalizeFirstCharacter(): String {
        return substring(0, 1).toUpperCase() + substring(1)
    }

textview.text = title.capitalizeFirstCharacter()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!