Skip to main content

Custom FontTextView in Android

Customize font from layout for TextView

In android layout textview with font-family option with three fonts are given by default.
If we have to add our own custom fonts from assert we have to do it by programmatically by adding these lines of code :

TextView name = (TextView)findViewById(R.id.name); 
Typeface type=Typeface.createFromAsset(getAssets(),"fonts/RobotoSlabRegular.ttf");
txtyour.setTypeface(type);


Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26.

Add your font files in the font folder. 


 Adding the font files in the resource directory

Creating a font family file in font folder


<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

In the layout XML file, set the fontFamily attribute to the font file you want to access.  

<TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:fontFamily="@font/lobster"/>
  
 

Adding fonts to style

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

Using fonts programmatically

Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
 
 
 

Below code Old way

Like this there are different ways to add customized fonts to textview in android. we will today learn the easiest way to do this.

Create a FontTextView.class:

@SuppressLint("AppCompatCustomView")
public class FontTextView extends TextView {

    public FontTextView(Context context) {
        super(context);        
        init(null, 0);    
    }

    public FontTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);        
        init(attrs, 0);    
    }

    public FontTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);        
        init(attrs, defStyleAttr);    
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public FontTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, 
                                                                int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);        
        init(attrs, defStyleAttr);    
    }

    private void init(AttributeSet attrs, int defStyleAttr) {
        TypedArray attrArray = getContext().obtainStyledAttributes(attrs,R.styleable.MyTextView, 
                                                                            defStyleAttr, 0);        
        initAttributes(attrArray);    
    }

    protected void initAttributes(TypedArray attrArray) {
        String textStyle = attrArray.getString(R.styleable.MyTextView_myTextStyle);
        if (textStyle == null || textStyle.equals(null) || textStyle.equals("")) {
            //do nothing it will override default typeface from android
        } else {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(),textStyle);
            setTypeface(tf);        
        }
    }
}

Create attrs.xml in values resource folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <declare-styleable name="MyTextView">
        <attr name="myTextStyle" format="string"></attr>
     </declare-styleable>
</resources>

In strings.xml in values resource folder:

<string name="robo_slab_regular">"font/RobotoSlabRegular.ttf"</string>


Now its time to use the FontTextView in layout:

<com.example.FontTextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="PM"
    android:textColor="@android:color/white"
    app:myTextStyle="@string/robo_slab_regular" />

That's all no need to do any extra code anymore!!






Comments

Popular posts from this blog

Vertical AutoScrolling TextView in Android

In android by default we can scroll the text in horizontal using marquee in layout, but if we want to scroll the text in vertical its not possible by default. So here we will learn to create a custom TextView which will auto-scroll in vertical direction. Source Code:  VerticalScrollingTextView-Android Create a AutoScrollingTextView.class which extends TextView: @SuppressLint ( "AppCompatCustomView" ) public class AutoScrollingTextView extends TextView { private static final float DEFAULT_SPEED = 65.0f ; public Scroller scroller ; public float speed = DEFAULT_SPEED ; public boolean continuousScrolling = true; public AutoScrollingTextView (Context context) { super (context) ; init( null, 0 ) ; scrollerInstance(context) ; } public AutoScrollingTextView (Context context , AttributeSet attrs) { super (context , attrs) ; init(attrs , 0 ) ; scr

Flexbox inside the RecyclerView as a LayoutManager (FlexboxLayoutManager).

Currently google has release the Flexbox which can be used for building flexible layouts using FlexboxLayout, it can be interpreted as an advanced LinearLayout because both layouts align their child views sequentially. For more detail on this flexbox-layout But here we are gonna work on Flexbox with RecyclerView. Flexbox with a large number of items in a scrollable container! Let's first see what are the Supported attributes / features comparison Due to some characteristics of the RecyclerView, some Flexbox attributes are not available/not implemented to the FlexboxLayoutManager. Here is a quick overview of the attributes/features comparison between the two containers. Attribute / Feature FlexboxLayout                FlexboxLayoutManager (RecyclerView) flexDirection flexWrap (except wrap_reverse ) justifyContent alignItems alignContent - layout_order - layout_flexGrow layout_flexShrink layout_alignSelf layout_fl

Android RecyclerView and StaggeredGridLayoutManager with Picasso/Glide

This project is there in GitHub https://github.com/yuvaraj119/Picasso-RecyclerView-StaggeredGridLayoutManager You can download and start customizing it for your project also. How to use with Picasso Picasso + RecyclerView + StaggeredGridLayoutManager Its the enhanced version of this project https://github.com/pohh/slotmachinepicasso were there was a problem with Picasso + RecyclerView + StaggeredGridLayoutManager shuffles resizable recycler views infinitely issue posted on github https://github.com/square/picasso/issues/918 I have made some changes now it works with Picasso and Glide without any shuffles and position change Currently this project is done with Picasso If you want to use it with Glide How to use with Glide Glide + RecyclerView + StaggeredGridLayoutManager Add dependencies for Glide https://github.com/bumptech/glide Remove Picasso library from dependency and remove all the codes of Picasso from MyGridAdapter.java and also from other p