Search code examples
androidtextview

How to make a custom TextView?


I'm trying to make a custom text view that has the font set from a given path. Please provide me any example and how I can make that with less code:

<TextView
   android:id="@+id/textView2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/accountInfoText"
   android:textColor="#727272"
   android:textSize="18dp" />

Solution

  • import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class FontTextView extends TextView {
    
    
        public FontTextView(Context context) {
          super(context);
          Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
          this.setTypeface(face); 
        }
    
        public FontTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
         Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
      this.setTypeface(face); 
        }
    
        public FontTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
         Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
      this.setTypeface(face); 
        }
    
        protected void onDraw (Canvas canvas) {
            super.onDraw(canvas);
            
           
        }
    
    }
    

    and in xml:

    <com.util.FontTextView
                        android:id="@+id/textView2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/accountInfoText"
                        android:textColor="#727272"
                        android:textSize="18dp" />