android -> set global font style

 

The home page sets a theme in the application in AndroidManifest.xml

<application
    android:name="com.qiyuan.congmingtou.app.CMTApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:persistent="true"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

  

 

in style.xml

 

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:windowNoTitle">true</item>
    <item name="android:typeface">serif</item>
</style>

 

 

There are 3 default font styles in Android,

serif,

monospace,

without,

 

*** If the third-party font is loaded globally, the control (such as TextView) needs to be rewritten

First put the downloaded TTF font file into assets/fonts/f3.ttf

 

Then override TextView like TextViewMy.java

package com.mft.test;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

/**
 * Created by tk on 2017/5/5 0005.
 */
public class TextViewMy extends TextView {
    public TextViewMy(Context context) {
        super(context);
        setTypeface() ;
    }
    public TextViewMy(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface() ;
    }
    public TextViewMy(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTypeface() ;
    }
    private void setTypeface(){
        // If the custom typeface fails to initialize, use the native typeface
        try{
            setTypeface(Typeface.createFromAsset(getContext().getAssets(),"fonts/f3.ttf"));
        }catch(Exception e){
            Log.i("MyApp", "Failed to load third-party font.");
        }

    }

}

 

 

' and then in the layout file you can use it like this

                    <com.mft.test.TextViewMy
                        android:text="A"
                        android:id="@+id/key_a"
                        android:tag="a"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@drawable/btn_zh_abc_key"
                        android:layout_weight="1"
                        android:textColor="@color/keyb_zh_abc_color"
                        android:textSize="@dimen/zh_keyb_abc_font_size"
                        android:gravity="center"
                        />

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326207701&siteId=291194637