Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize first letter of TextView in an Android layout xml file

I have a TextView in a layout xml file like this:

<TextView
   android:id="@+id/viewId"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/string_id" />

My string is specified like this:

<string name="string_id">text</string>

Is it possible to make it display "Text" instead of "text" without java code?
(and without changing the string itself either)

like image 945
qwertzguy Avatar asked Dec 20 '22 00:12

qwertzguy


2 Answers

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);
    }
}
like image 148
Hyrum Hammon Avatar answered Jan 31 '23 14:01

Hyrum Hammon


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

}
like image 37
Jonas Borggren Avatar answered Jan 31 '23 14:01

Jonas Borggren