Where in res folder should I put my font file (TTF)?
Using Custom Font
First step is to pick a font that you want to use.
Second create a Fonts folder in your assets directory and copy your font there.
NB: you can put your font everywhere on asssets folder but this is the way that i do!!
That’s it for the setup, now on to the code.
To access your custom font, you have to use the Typeface class in the Android SDK to create a typeface that Android can use, then set any display elements that need to use your custom font appropriately. To demonstrate, you can for exemple create two text views on your main screen, one using the default Android Sans font, and the other using your custom font. The layout is below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/DefaultFontText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="Here is some text." />
<TextView
android:id="@+id/CustomFontText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="Here is some text.">
</TextView>
</LinearLayout>
The code to load and set the custom font is straight forward as well, and is shown below.
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);
}
}
you can see the result:
You can create the font in asset folder (i.e asset/fonts/roboto.ttf).
Then, create an appropriate class for your TextView:
// RobotoFont class
package com.my.font;
public class RobotoFont extends TextView {
public RobotoFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public RobotoFont(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RobotoFont(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf"));
}
else if(style == Typeface.ITALIC)
{
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Italic.ttf"));
}
else
{
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
}
}
}
and finally, update your layout:
//main.xml
//replace textview with package name com.my.font.RobotoFont
<com.my.font.RobotoFont
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With