Android 中全局更换字体的方法
在我们开发Android程序的时候通常会遇到更改全局字体的需求,我目前能想到的解决方案有三种,下面我们来进行逐一分析:
第一种方式就是自定义控件,毫无疑问这个一定能解决我们的问题,只需要把我们之前用的控件换成我们自定义的控件就好,缺点是如果是多种控件我们就要自定义多种相对应的View,太过麻烦,工作量太大
第二种是利用递归的思想遍历RootView 中的所有View进行判断并进行字体的更改,缺点是有损性能
第三种方法是利用setFactory方法来更换字体,这个也是我想主要说的,这里我们需要字体.ttf文件,如图:
主要代码如下:
- package com.example.mac.allchangetextsizetest;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.content.res.Configuration;
- import android.graphics.Typeface;
- import android.support.v4.view.LayoutInflaterCompat;
- import android.support.v4.view.LayoutInflaterFactory;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatDelegate;
- import android.util.AttributeSet;
- import android.util.DisplayMetrics;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- public class MainActivity extends AppCompatActivity {
- public static Typeface typeface;
- public static Typeface typeface1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- if (typeface == null) {
- typeface = Typeface.createFromAsset(getAssets(), "Arial.ttf");
- }
- if (typeface1 == null) {
- typeface1 = Typeface.createFromAsset(getAssets(), "ARIALNI.TTF");
- }
- LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory()
- {
- @Override
- public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
- {
- AppCompatDelegate delegate = getDelegate();
- View view = delegate.createView(parent, name, context, attrs);
- if ( view!= null && (view instanceof TextView)) {
- ((TextView) view).setTypeface(typeface1);
- }
- if(view!=null && (view instanceof EditText)) {
- ((EditText) view).setTypeface(typeface);
- }
- return view;
- }
- });
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button button = (Button)findViewById(R.id.button);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // changeTextSize(MainActivity.this,2);
- finish();
- Intent intent = new Intent(MainActivity.this, MainActivity.class);
- startActivity(intent);
- }
- });
- }
效果图如下:
这样 我们的变换字体就OK了