一種簡單的Android 中全域性更換字型的方法
阿新 • • 發佈:2019-01-28
在我們開發Android程式的時候通常會遇到更改全域性字型的需求,我目前能想到的解決方案有三種,下面我們來進行逐一分析:
第一種方式就是自定義控制元件,毫無疑問這個一定能解決我們的問題,只需要把我們之前用的控制元件換成我們自定義的控制元件就好,缺點是如果是多種控制元件我們就要自定義多種相對應的View,太過麻煩,工作量太大
第二種是利用遞迴的思想遍歷RootView 中的所有View進行判斷並進行字型的更改,缺點是有損效能
第三種方法是利用setFactory方法來更換字型,這個也是我想主要說的,這裡我們需要字型.ttf檔案,如圖:
主要程式碼如下:
這樣只要我們的Activity 繼承自上面的Activity那麼其中的TextView 和 EditText 都會變成我們設定成的字型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了