Typeface fontRobo = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Black.ttf");
viewTotalValue.setText(total.toString());
Asked
Active
Viewed 9,173 times
3

Bucket
- 7,415
- 9
- 35
- 45

user3153051
- 31
- 1
- 2
-
2Unfortunately this is not possible – A.S. Mar 27 '14 at 13:56
-
possible duplicate of [Accessing a font under assets folder from XML file in Android](http://stackoverflow.com/questions/6746665/accessing-a-font-under-assets-folder-from-xml-file-in-android) – Siruk Viktor Mar 27 '14 at 14:00
-
1If you dont want to do this to every TextView you can create class that extends TextView and set your Typeface in there. Then you can use that class in your xml files like **com.your.customview.package.CustomFontTextView**. – vilpe89 Mar 27 '14 at 14:00
3 Answers
19
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"
/>

A.S.
- 4,574
- 3
- 26
- 43
3
You could create a custom class that extends TextView
, let's say FontTextView
.
Define a special string attribute for that class, let's say "font".
Then, in your FontTextView
constructor based on the value of the font
attribute, choose the appropriate Typeface
from your assets.
See:

Community
- 1
- 1

Ovidiu Latcu
- 71,607
- 15
- 76
- 84
3
Extending TextView just for setting font looks so expensive and not good. The most clear way is to use Android Data-Binding Framework and BindingAdapter:
@BindingAdapter("bind:font")
public static void setTypeface(TextView textView, int index) {
Typeface myTypeface = //retrieve typeface from cache, based on some font index
textView.setTypeface(myTypeface);
}
declaration in xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:font="@{R.attr.Proxima_Nova_Regular}"
/>
attrs.xml:
<attr name="Proxima_Nova_Regular"/>
<attr name="Proxima_Nova_Black"/>
<attr name="Proxima_Nova_Bold"/>
or use resources integers same way
In your cache/creator helper determine dependencies between R.attr.Your Font and instance of typeface.

Beloo
- 9,723
- 7
- 40
- 71