Today we are going to introduce a TextView instead of a picture to achieve App optimization and icon adaptation. The image size and other Settings still use TextView’s native methods.

Here’s the GitHub link to this article: github.com/OCNYang/Fon…

First, let’s take a look at the effects:

These are really just TextView text

If you look at the image above, at first glance you might think that it is all displayed using an ImageView, but you would be wrong. It is all done using a TextView (and certainly not with a TextView background).

At ordinary times we are in development, the picture is everywhere and essential part of to try their best to make the picture to achieve the effect of adaptation we may need to: provide more floor plans according to the different resolution, regardless of whether or not this way, under normal circumstances we cut three or more code sometimes has always worked on some models. At this time, you may think of using.9 pictures. At this time, let alone whether your UI sister will provide.9 pictures for our Android terminal alone (I believe your UI will make.9), but the.9 pictures have certain limitations, it can only be stretched in part of the picture.

This article is not to introduce how to do picture adaptation, but to introduce a way to use the font library, we use the form of TextView to display pictures, and we can normally use android:textSize attribute to set the size of pictures at will!

Actually, the way we’re going to display an image in a TextView, I’d rather say it’s more accurately a TextView that displays an icon, because the image here is not really a large image but rather a vector image that you can stretch at will. Of course, you can display images this way if you wish.

With all this talk, is your broadsword already thirsty? It’s actually pretty easy to do this, just by setting a font for the TextView, so don’t worry, start right away.

Set the font for the TextView

As we all know, in Android, if we want to change the font, in addition to introducing the font library we need, we also need to manually set the font for our TextView. How to set the font? It’s really simple.

textView.setTypeface(Typeface tf);  Copy the code

Although this is only one line of code, there will be a large number of TextViews in our project. Should we set them up one by one? Think of this is also a headache, here is a convenient way to solve the font setting problem, one line of code.

Method 1: Utility class & recursive traversal

Before we look at the code, let’s look at the idea. The idea is pretty simple. We provide a root layout, write a method to recursively traverse the entire root layout, and if it’s a textView, set the font. The idea is very simple, I believe the code is very simple, is a recursive method.

public class FontHelper {
    public static final String DEF_FONT = "fonts/ocnyangfont.ttf";

    public static final void injectFont(View rootView) {
        injectFont(rootView, Typeface.createFromAsset(rootView.getContext().getAssets(),
                DEF_FONT));
    }

    private static void injectFont(View rootView, Typeface typeface) {
        if (rootView instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) rootView;
            int childViewCount = viewGroup.getChildCount();
            for(int i = 0; i < childViewCount; i++) { injectFont(viewGroup.getChildAt(i), typeface); }}else if(rootView instanceof TextView) { ((TextView) rootView).setTypeface(typeface); }}}Copy the code

Defines a utility class that provides two static methods, but the core is both

public static final void injectFont(View rootView, Typeface tf)Copy the code

In this method, we first determine if the rootView we’re giving is a ViewGroup. If it is a ViewGroup, we iterate through all of its child views and recursively call this method until we’re done. If we find a view that’s a TextView, We call the setTypeface method to set the font. Ok, from this utility class we can also see that our fonts are placed under Assets /fonts.

Finally, we use the font library in our activity, formally utilizing the above utility classes, so our code will be simple.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FontHelper.injectFont(findViewById(android.R.id.content));
}Copy the code

Just one line of code, fonthelper.injectFont (findViewById(Android.r.i. D.c ontent)); We’re done setting the font for all of our TextViews.

Method 2: LayoutInflate

If you are not familiar with the use of LayoutInflateFactory, check out Hongyang’s post exploring the LayoutInflate setFactory.

Let’s write a custom LayoutInflaterFactory:

public class IconFontLayoutFactory implements LayoutInflaterFactory {

    private static Typeface sTypeface;
    private AppCompatDelegate mAppCompatDelegate;

    public IconFontLayoutFactory(Context context,
                                 AppCompatDelegate appCompatDelegate) {
        if (sTypeface == null) {
            sTypeface = Typeface.createFromAsset(context.getAssets(),
                    "fonts/ocnyangfont.ttf");
        }
        mAppCompatDelegate = appCompatDelegate;
    }

    @Override
    public View onCreateView(View parent, String name, Context context,
                             AttributeSet attrs) {
        View view = mAppCompatDelegate.createView(parent, name, context, attrs);
        if (view instanceof TextView) {
            ((TextView) view).setTypeface(sTypeface);
        }
        returnview; }}Copy the code

We’ll keep the fonts under Assets /fonts.

You can then call the following code in your BaseActivity onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {

        LayoutInflaterCompat.setFactory(getLayoutInflater(),
                new IconFontLayoutFactory(this,getDelegate()));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}Copy the code

Be sure to call it before super.oncreate.

This method can call setTypeFace for TextView and its subclasses when they are created. For font libraries, you can even lazily load them in SplashActivity if you need to.

There are two global Settings provided here. Sometimes we just need to set some textViews. In this case, we can choose to manually set a specific TextView, or we can use a custom View to do this. Also very simple here is not wordy, detailed code can be downloaded here to view the source code).

This is just how to set up a font. You probably already know that a font is a font, not a picture. Don’t panic, here is how to introduce a cool font library and create your own unique picture font library.

Use of fontawesome Font library

Before we can start using it, we need to go to github.com/FortAwesome… Download the font library (which is included in the source code for this article). All we need is a file -fontawesome-webfont. TTF. This file is located under the /fonts/ directory. Copy the TTF file into assets of your project. By common practice or common understanding, we will probably put it in assets/fonts (note, if you don’t have this directory, create it!). .

Ok, now that we’re all set, let’s go ahead and use it. Look at my XML layout file:

<LinearLayout
    //...
    >

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:textSize="58sp"
        android:textColor="#ff995533"
        android:layout_height="wrap_content"
        android:text=""/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:textSize="118sp"
        android:textColor="#ff9ff533"
        android:layout_height="wrap_content"
        android:text=""/ > / /... </LinearLayout>Copy the code

When we look at the layout file, we see that it is the same as usual, giving the textSize or textColor attribute, which definitely controls the size and color of the image we need to display!

If you look carefully, you’ll notice how weird these TextView texts are. In fact, the text corresponds to the picture relative to. Now, however, we have another problem. How do we know which text represents which picture? Here is a url where you can see a table of the physical text and its corresponding image.

Fortawesome. Making. IO Font – Awesom…

In this article source we provide a string. XML file picture character comparison table, can be directly used in the project. You can also use it in your own string file by Ctrl + F in the string. XML file above.

Oh, by the way, if you’ve noticed, we’ve inadvertently solved an image size problem here, because we can change the size of one text at will, so there’s no need to provide multiple images to fit different screens.

If you’re wondering, the Font Awesome library does not necessarily meet all of our needs. Now let’s teach you how to make your own font library.

Make your own picture font library

Before creating your own picture font library, of course, you should first look up some beautiful ICONS you like. Here is the dry goods benefit mode.

Icon dry

For use, the most important is to find some reliable material site

www.iconfont.cn/ icomoon. IO/app / # / selec… Github.com/mikepenz/An…

The first site is the icon library provided by Ali. Basically, you can search any icon you need, which is very convenient and supports color and size Settings, enough to meet our needs:

Ali Iconfont icon library

Custom ICONS

No matter how complete the ICONS provided by these websites are, they may not be able to satisfy greedy you or your family’s pursuit of perfection (pretentiousness) to the extreme UI. So if the ICONS in the App are made by yourself, can they be packaged into a font library mixed with existing ICONS on the Internet? The answer is yes, we are going to make our own font library. For example, you can rely on iconfont.com to upload your own SVG icon, and then choose from it.

About iconfont the use of the site can refer to the official manual (also can skip, follow me to learn how to directly generate your own font library) : www.iconfont.cn/help/platfo…

Generate your own icon font library on demand

We take iconfont library as an example to teach you the whole process of creating your own picture font library (all the steps below, you don’t need to register an account, can directly use).

Firstly, select the icon you want to generate into the font library on iconfont website. You can choose from the font library of the website or select the icon uploaded by yourself in my icon library. Add these ICONS to the library (i.e. add them to the shopping cart) :

Select your favorite icon

Add to shopping cart

After selecting the icon of the font library you want to generate, click open library (Shopping cart) in the upper right corner of the website, you can see all the ICONS you choose in the library, click download code after confirming:

Open the library and download the code to get a zip package

After unzipping, you can see the generated library

In the unzipped folder, we see many files. The file ending in.ttf is our own font library, and the three.html files correspond to the encoding used on different platforms. The encoding we will use in Android development is the corresponding &# XXXXX in the demo_Unicode. HTML file. Form encoding.

If you are careful, you will find that although the generated font library contains many ICONS, it is only a few kilobytes in size. What is more valuable is that no matter how large the size is set, it can still preserve the same clarity. Of course, you can also see this solution as one of the apK slimming parts.

This article Demo source code download address: github.com/OCNYang/Fon…

英 文 名 称 : How to Use FontAwesome in an Android App