[Android] How to customize fonts

Source: Internet
Author: User
Tags repetition

In the project to unify with the designer font, Android:typeface only supports the system three kinds of fonts. What better way to do it?

You need to replace the custom font for the entire app.

Solution 1) Android default method #1

You can find the view by ID and then set the font for each of them. In the case of a single view, it doesn't look that scary either.

Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");TextView view = (TextView) findViewById(R.id.activity_main_header);view.setTypeface(customFont);

But in the case of a lot of textview, button and other text components, I'm sure you won't like this method. :D

2) Android default method #2

You can create a subclass for each text component, such as TextView, Button, and so on, and then load the custom font in the constructor.

PublicClassBrandtextviewExtendsTextView {PublicBrandtextview (context context, AttributeSet attrs,int Defstyle) {Super (context, attrs, Defstyle); }public brandtextview (context context, AttributeSet Attrs) { Span class= "Hljs-keyword" >super (context, attrs); } public brandtextview (context context) { super (context); public void setTypeface (Typeface TF, int style) {if (style = = Typeface.bold) {super.settypeface (Typeface.createfromasset (GetContext (). Getassets (), else {super.settypeface (Typeface.createfromasset ( GetContext (). Getassets (),  "Fonts/yourcustomfont.ttf"); } } }

Then just replace the standard text control with your custom (for example, Brandtextview to replace TextView).

<com.your.package.BrandTextView         android:layout_width="wrap_content"

You need to replace the custom font for the entire app.

Solution 1) Android default method #1

You can find the view by ID and then set the font for each of them. In the case of a single view, it doesn't look that scary either.

Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");TextView view = (TextView) findViewById(R.id.activity_main_header);view.setTypeface(customFont);

But in the case of a lot of textview, button and other text components, I'm sure you won't like this method. :D

2) Android default method #2

You can create a subclass for each text component, such as TextView, Button, and so on, and then load the custom font in the constructor.

PublicClassBrandtextviewExtendsTextView {PublicBrandtextview (context context, AttributeSet attrs,int Defstyle) {Super (context, attrs, Defstyle); }public brandtextview (context context, AttributeSet Attrs) { Span class= "Hljs-keyword" >super (context, attrs); } public brandtextview (context context) { super (context); public void setTypeface (Typeface TF, int style) {if (style = = Typeface.bold) {super.settypeface (Typeface.createfromasset (GetContext (). Getassets (), else {super.settypeface (Typeface.createfromasset ( GetContext (). Getassets (),  "Fonts/yourcustomfont.ttf"); } } }

The

Then just needs to replace the standard text control with your custom (for example, Brandtextview to replace TextView).

<com.your.package.brandtextview android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "View with custom Font"/> <com.your.package.brandtextview android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:textstyle= "bold"  Android:text= "View with custom font and bold typeface"/>     

Also, you can even add custom font properties directly to the XML. To implement this, you need to define your own declare-styleable properties and then parse them in the component's constructor.

Here's a good article to show you how to customize the properties of a control in order not to cover the basics.

http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/

In most cases, this method is not bad, and there are some advantages (for example, switching font weight and so on, the font can be defined in the typeface attribute of the component XML file). But I think this implementation is still too heavyweight, and rely on a lot of template code, for a simple task of replacing fonts, a little more than the candle.

3) My Solution

The ideal solution is to customize the theme and then apply it to a global or an activity.
Unfortunately, the properties of Android android:typeface can only be used to set fonts embedded in the system, not user-defined fonts (such as fonts in the assets file). That's why we can't avoid loading and setting fonts in Java code.

So I decided to create a helper class that makes the operation as simple as possible. How to use:

"fonts/YourCustomFont.ttf");

And this line of code will be used to load all the TextView-based text components (TextView, buttons, RadioButton, ToggleButton, etc.) without regard to the layout hierarchy of the interface.

Standard (left) and custom (right) font usage.

How did this happen? Very simple:

PublicStaticvoidApplyfont (Final context Context,final View root, final String fontname) {try {if (Root instanceof ViewGroup) {ViewGroup ViewGroup = (viewgroup) root; for (int i = 0; i < Viewgroup.getchildcount (); i++) Applyfont (context, Viewgroup.getchildat (i), fontname); } else if (Root instanceof TextView) ((TextView) root). Settypeface (Typeface.createfromasset (Context.getassets (), fontname)); } catch (Exception e) {log.e (TAG, String.Format ( "Error occured When trying to apply the%s font for%s view ", FontName, Root)"; E.printstacktrace (); }}

As you can see, all you need to do is to traverse the TextView-based text component from the layout.

You can download it here to the sample code, which has FontHelper specific usage.

Some ideas

In many projects, I have encountered similar requirements, the early adoption of the second approach, but the downside is that for third-party components, you need to modify someone else's code in order to implement a custom font, which violates the OC (Open & Close) principle, open to the extension, the modification closed.

Just see the third kind of time, is also surprised for heaven and man, let's not say the result, I think this active thinking is very important, it is worth learning reference.

But in the end by the team's people rejected, the reason is against the component design principles, the implementation of a slightly rough way. Then I think about it, one is to do a good memory management (seems to cause memory problems), the view state changes, but also to repeat loading (screen, onresume, etc.), is definitely not a simple job.

So tentatively using the first method, typeface uses the singleton and sets the font when needed.

I personally think that the first kind is still a physical activity, and later, the code repetition rate is very high, which violates the dry principle.

When I was on the subway, I suddenly thought of Di (Dependency Inject). There are already some di frameworks, such as butterknife, that should be written like this:

@CustomFont(R.id.textView) TextView textView

Or

@InjectView(id=R.id.textView, customFont=true) View anyView@InjectView(id=R.id.textView, customFont=true, customFont="fonts/ltfz.ttf") View anyView

It is better to write the code in this way than to repeat the settypeface.

Currently our project has not used this kind of di framework, and so on later introduced, using the second kind of injection, write it should be very cool.

Specifically read my blog: "Translate" Android: Better Custom Font method

android:layout_height=  "wrap_content" android:text= " View with custom Font "/> <com.your.package.brandtextview" Span class= "Hljs-attribute" >android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:textstyle= "bold"  Android:text= "View with custom font and bold typeface"/>     

Also, you can even add custom font properties directly to the XML. To implement this, you need to define your own declare-styleable properties and then parse them in the component's constructor.

Here's a good article to show you how to customize the properties of a control in order not to cover the basics.

http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/

In most cases, this method is not bad, and there are some advantages (for example, switching font weight and so on, the font can be defined in the typeface attribute of the component XML file). But I think this implementation is still too heavyweight, and rely on a lot of template code, for a simple task of replacing fonts, a little more than the candle.

3) My Solution

The ideal solution is to customize the theme and then apply it to a global or an activity.
Unfortunately, the properties of Android android:typeface can only be used to set fonts embedded in the system, not user-defined fonts (such as fonts in the assets file). That's why we can't avoid loading and setting fonts in Java code.

So I decided to create a helper class that makes the operation as simple as possible. How to use:

"fonts/YourCustomFont.ttf");

And this line of code will be used to load all the TextView-based text components (TextView, buttons, RadioButton, ToggleButton, etc.) without regard to the layout hierarchy of the interface.

Standard (left) and custom (right) font usage.

How did this happen? Very simple:

PublicStaticvoidApplyfont (Final context Context,final View root, final String fontname) {try {if (Root instanceof ViewGroup) {ViewGroup ViewGroup = (viewgroup) root; for (int i = 0; i < Viewgroup.getchildcount (); i++) Applyfont (context, Viewgroup.getchildat (i), fontname); } else if (Root instanceof TextView) ((TextView) root). Settypeface (Typeface.createfromasset (Context.getassets (), fontname)); } catch (Exception e) {log.e (TAG, String.Format ( "Error occured When trying to apply the%s font for%s view ", FontName, Root)"; E.printstacktrace (); }}

As you can see, all you need to do is to traverse the TextView-based text component from the layout.

You can download it here to the sample code, which has FontHelper specific usage.

Some ideas

In many projects, I have encountered similar requirements, the early adoption of the second approach, but the downside is that for third-party components, you need to modify someone else's code in order to implement a custom font, which violates the OC (Open & Close) principle, open to the extension, the modification closed.

Just see the third kind of time, is also surprised for heaven and man, let's not say the result, I think this active thinking is very important, it is worth learning reference.

But in the end by the team's people rejected, the reason is against the component design principles, the implementation of a slightly rough way. Then I think about it, one is to do a good memory management (seems to cause memory problems), the view state changes, but also to repeat loading (screen, onresume, etc.), is definitely not a simple job.

So tentatively using the first method, typeface uses the singleton and sets the font when needed.

I personally think that the first kind is still a physical activity, and later, the code repetition rate is very high, which violates the dry principle.

When I was on the subway, I suddenly thought of Di (Dependency Inject). There are already some di frameworks, such as butterknife, that should be written like this:

@CustomFont(R.id.textView) TextView textView

Or

@InjectView(id=R.id.textView, customFont=true) View anyView@InjectView(id=R.id.textView, customFont=true, customFont="fonts/ltfz.ttf") View anyView

It is better to write the code in this way than to repeat the settypeface.

Currently our project has not used this kind of di framework, and so on later introduced, using the second kind of injection, write it should be very cool.

Specifically read my blog: "Translate" Android: Better Custom Font method

[Android] How to customize fonts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.