I applied a custom font to a TextView
, but it doesn't seems to change the typeface.
Here is my code:
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(myTypeface);
Can anyone please get me out of this issue?
The best way to do it From Android O preview release is this way:
It works only if you have android studio-2.4 or above
Resource Directory window appears.
R.font.dancing_script
,R.font.la_la
, andR.font.ba_ba
.Next we must create a font family:
Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
Adding fonts to a TextView:
As from the documentation
All the steps are correct.
With Android 8.0 using Custom Fonts in Application became easy with
downloadable fonts
. We can add fonts directly to theres/font/ folder
in the project folder, and in doing so, the fonts become automatically available in Android Studio.Now set
fontFamily
attribute to list of fonts or click on more and select font of your choice. This will addtools:fontFamily="@font/your_font_file"
line to your TextView.This will Automatically generate few files.
1. In values folder it will create
fonts_certs.xml
.2. In Manifest it will add this lines:
3.
preloaded_fonts.xml
Update answer: Android 8.0 (API level 26) introduces a new feature, Fonts in XML. just use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26.
see this link
Old answer
There are two ways to customize fonts :
Way 1 : Refrection Typeface.class ||| best way
call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts
AppController.java
FontsOverride.java
Way 2: use setTypeface
for special view just call setTypeface() to change font.
CTextView.java
FontUtils.java
Since I was not satisfied with all the presented solutions on SO, I've come up with mine. It's based on a little trick with tags (i.e. you can't use tags in your code), I put the font path there. So when defining views, you can do either this:
or this:
Now you can either explicitly access / setup the view as:
or just setup everything via:
And what is the magic class you ask? Mostly glued from another SO posts, with helper methods for both activity and fragments:
I know there are good answers already, but here's a fully working implementation.
Here's the custom text view:
Here's the custom attributes. This should go to your
res/attrs.xml
file:And here's how you use it. I'll use a relative layout to wrap it and show the
customAttr
declaration, but it could obviously be whatever layout you already have.I've successfully used this before. The only difference between our implementations is that I wasn't using a subfolder in assets. Not sure if that will change anything, though.