In this post we will be learning how to use custom fonts in your project. First i will mention all the necessary steps to do it and then we will check code explanation for complex methods.
Step 1: Download below files and integrate them in your project:
Step 2: Create attrs.xml (if not present) under your res/values folder. Place below code
Step 4: Place Custom fonts under your assets folder like this
Step 5: Refer them in your strings.xml like
Explainations:
Happy Coding ...
Step 1: Download below files and integrate them in your project:
Step 2: Create attrs.xml (if not present) under your res/values folder. Place below code
<?xml version="1.0" encoding="utf-8"?>Step 3: Download Custom Fonts. You can use any custom font which you need I have used arial.ttf fonts you can download it from below links
<resources>
<declare-styleable name="CustomTextView">
<attr name="fontFace" format="string" />
</declare-styleable>
</resources>
Step 4: Place Custom fonts under your assets folder like this
Step 5: Refer them in your strings.xml like
<!-- Fonts -->Step 6: You can use above custom type face in your layout xmls like below:
<string name="fonts_normal">arial.ttf</string>
<string name="fonts_bold">arial_bold.ttf</string>
<package.name.CustomTextView
xmlns:coop="http://schemas.android.com/apk/res-auto"
style="@style/title_font_gray"Its Done, Hopefully you can easily integerate this in your projects.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
coop:fontFace="@string/fonts_normal" />
Explainations:
- TypeFaceHelper- This class allows you to load fonts from your assets directory.
- CustomTextView- This class takes care to set typeface on your custom textviews. This class also set default typeface or normal font if fontface is not provided in your layout xml. Below lines of code take care of it.
String fontFace = typedArray.getString(R.styleable.CustomTextView_fontFace);
if (fontFace == null) {
fontFace = context.getString(R.string.fonts_normal);
}
- CustomTextView class also has some helper methods like-
public void useBoldFont(){You can use above methods directly from your code without updating layout xml file.
String fontFace = getContext().getString(R.string.fonts_bold);
setTypeface(TypefaceHelper.getTypeface(getContext(), fontFace));
}
public void useNormalFont(){
String fontFace = getContext().getString(R.string.fonts_normal);
setTypeface(TypefaceHelper.getTypeface(getContext(), fontFace));
}
Happy Coding ...
No comments:
Post a Comment