天天看點

Android如何使用自定義字型

做應用時,使用text顯現出的文字都屬于系統預設的字型,有時候達不到自己的需求

Android系統自帶了三種字型,分别是sans、serif和monospace,使用方式是在xml中配置typface即可

<TextView
        android:id="@+id/header_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:textStyle="bold"
        android:type
        android:textColor="@color/white" />
           

如果想使用其他的字型,可以按照如下方法:

首先下載下傳想要顯示的字型的ttf檔案,并且放到assets檔案夾下的fonts檔案夾中(fonts自己建立一個即可)

然後在代碼中設定控件的屬性即可:

// 使用自定義字型
		Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/YEGENYOUTEKAI9-28_0.TTF");
		headerTextView.setTypeface(typeface);
           

将字型檔案存放在assets檔案夾中僅是一種方法,儲存為檔案或者其他形式也能實作

Android如何使用自定義字型

如果想要将全部字型都更改,目前我所知道的辦法是周遊所有控件,如果有更好的辦法,歡迎大家提供補充

public static void changeFonts(ViewGroup root, Activity activity) {  

		       Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "fonts/xxx.ttf");  

		       for (int i = 0; i < root.getChildCount(); i++) {  
		    	   
		           View v = root.getChildAt(i);  
		           
		           if (v instanceof TextView) {  
		              ((TextView) v).setTypeface(typeface);  
		           } else if (v instanceof Button) {  
		              ((Button) v).setTypeface(typeface);  
		           } else if (v instanceof EditText) {  
		              ((EditText) v).setTypeface(typeface);  
		           } else if (v instanceof ViewGroup) { 
		        	   // 遞歸調用
		              changeFonts((ViewGroup) v, activity);  
		           }  

		       }  

		    }