Wednesday, August 19, 2015

How to change EditText font size in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#bde9cb"
    >
    <!--
        android:textSize
            Size of the text. Recommended dimension type for text
            is "sp" for scaled-pixels (example: 15sp).

            Must be a dimension value, which is a floating point
            number appended with a unit such as "14.5sp".
            Available units are: px (pixels), dp (density-independent
            pixels), sp (scaled pixels based on preferred font size),
            in (inches), mm (millimeters).
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Default font size"
        />
    <EditText
        android:id="@+id/et2"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="Font size 25dp"
        android:padding="10dp"
        android:layout_below="@+id/et"
        android:textSize="25dp"
        />
    <EditText
        android:id="@+id/et3"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_below="@+id/et2"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.util.TypedValue;
import android.widget.EditText;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        EditText et = (EditText) findViewById(R.id.et);
        EditText et2 = (EditText) findViewById(R.id.et2);
        EditText et3 = (EditText) findViewById(R.id.et3);

        /*
            setTextSize (int unit, float size)
                Set the default text size to a given unit and value

                Parameters
                unit : The desired dimension unit.
                size : The desired size in the given units.
         */
        et3.setTextSize(TypedValue.COMPLEX_UNIT_DIP,20);

        // Set the default text of third EditText
        et3.setText("Font size 20dp programmatically");
 }
}
More android examples