Custom Edit Text Example

This example will show you how can you create and work with  custom edit text  in android application.

In this example we are going to change the font_type(font_typefae)  of edit text.

Steps :-

1) Create one java file that extends EditText.

2) Create one attrs.xml file in values folder where you can add your custom tag.

3) Create assets folder and put your font inside that .

4) Use your custom Tag in xml file.


Open your string.xml adn add your text name like below.

string.xml

<resources>
    <string name="app_name">myprojecttest</string>
    <string name="action_settings">Settings</string>


    <string name="font_Pacifico">Pacifico.ttf</string>
               //name you want   //font name exactly same as in assets folder
</resources>



attrs.xml

<resources>

    <declare-styleable name="editText">
        <attr name="font_type" format="string"/>
    </declare-styleable>

</resources>


Create one java name file and give name CustomEditText.java .


CustomEditText.java

public class CutomEditText extends EditText {
    public CutomEditText(Context context) {
        super(context);
    }

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

    public CutomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setAttribute(context, attrs);
    }

    public void setAttribute(Context context,AttributeSet attrs)
    {
        TypedArray attributes = context.obtainStyledAttributes(attrs,R.styleable.editText);
        String fon_Type= attributes.getString(R.styleable.editText_font_type);

        if(fon_Type != null || fon_Type != "")
        {
            Typeface typeface=Typeface.createFromAsset(context.getAssets(),fon_Type);
            setTypeface(typeface);
        }

    }

Main.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"   
 xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"    
android:layout_width="match_parent"   
 android:layout_height="match_parent"  
  android:padding="20dp">


        <com.myprojecttest.CutomEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="H E L L o"         
   app:font_type="@string/font_Pacifico"/>

    <com.myprojecttest.CutomEditText   
     android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="C U S T O M   E D I T  T E X T" 
       app:font_type="@string/font_Pacifico"/>

</LinearLayout>



Output



Comments