Tuesday, August 18, 2015

How to change EditText font 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="#e9e6cb"
    >
    <!--
        android:fontFamily
            Font family (named by string) for the text.
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Default font family"
        />
    <EditText
        android:id="@+id/et2"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="Sans serif thin font"
        android:padding="10dp"
        android:fontFamily="sans-serif-thin"
        android:layout_below="@+id/et"
        />
    <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.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
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);

        /*
            setTypeface (Typeface tf)
                Sets the typeface and style in which
                the text should be displayed.
         */
        et3.setTypeface(Typeface.MONOSPACE);

        // Set the default text of third EditText
        et3.setText("Monospace font");
 }
}
More android examples