how to set Android Typeface from xml

user3153051 picture user3153051 · Mar 27, 2014 · Viewed 8.4k times · Source
Typeface fontRobo = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Black.ttf");
viewTotalValue.setText(total.toString());

Answer

A.S. picture A.S. · Mar 27, 2014

You could create your own TextView by overriding the TextView like this:

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setType(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setType(context);
    }

    public MyTextView(Context context) {
        super(context);
        setType(context);
    }

    private void setType(Context context){
        this.setTypeface(Typeface.createFromAsset(context.getAssets(),
                    "foo.ttf"));

        this.setShadowLayer(1.5f, 5, 5, getContext().getResources().getColor(R.color.black_shadow));
    }
}

And use it like this:

<com.your.project.package.MyTextView
        android:id="@+id/oppinfo_mtv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"  
        android:text="Player 1"
        />