Tuesday, January 27, 2015

Set Third-party Font in Android

Continue from previous lesson, Create Android View in Java Class. In this post, I will teach how to import third-party font in android app.

If you create TextView in XML layout, there are two attribute for set font exist.
  • android:fontfamily, and
  • android:typeface

Both attribute use default font, only can set style of the font.

So, how to use custom or third-party font in android app?
There are several way, but all solution need Java class.


Let begin with firts part,
First, if you use android studio, you need create Asset Folder.

Right-click on app > New > Folder > Assets Folder


Then, I create 'fonts' directory in Assets Folder like below,

Right-click on assets > New > Directory



Second, download or choose any font you want use in your app. Then, copy and put it inside assets/fonts folder. For this lesson, i will use square_unique font.



Now we can start the lesson,
code to call font from asset is like below

Typeface typeface = Typeface.createFromAsset(context.getAssets(),
                "fonts/Square Unique Thin.ttf");


And below is how to set custom font for a View, at line 60



Sample Running :





And below I call TextView from XML layout and set font in Java class,
Firstly, need add id for TextView in activity_main.xml,



Then, we can call TextView from activity_main.xml in MainLayout.java, from line 43 to line 46


Sample Running :





Here the last method I know how to set third party font in TextView by create custom widget  and this is the difficult part for this lesson.

Firstly, need add new declare-styleable in res/values/attrs.xml,



Second, add Java class for customize TextView,



And finally, change adding CustomTextView in activity_main.xml. At line 25, there are new attribute exist after create it at attrs.xml


Sample Running :




code for MainLayout.java same like previous method and code for MainActivity.java still same like previous post..below is the code..

MainLayout.java


MainActivity.java




So, this is the end, method above you also can use it for other view like Button, EditText and etc.

If you have problem or something to ask something related to java...
you can email or comment on this post...
I will try to find the solution and share it with you..












you can test it by your self..
i hope you like this souce code...
and please give some comment....
                                                                                                                                                      Created By : Z-man, 2015

No comments:

Post a Comment