標籤:url and param 分享圖片 地址 格式 建立 ring 繼承
前言:我們都知道,Android中預設的字型是黑體,而大多數app也都是使用的這種字型,但我們發現,大多數app中,個別地方字型非常好看,例如app的標題列,功能表列等地方,那他們是怎麼做到的呢?有兩種方式,第一是圖片來代替文字,第二,就是今天我要教大家的自訂字型。
開發環境:
Android Studio 2.2.2
compileSdkVersion 25
buildToolsVersion "25.0.0"
minSdkVersion 19
targetSdkVersion 25
compile ‘com.android.support:appcompat-v7:25.0.0‘
提示:使用項目時注意開發環境的更改,以免造成不必要的時間浪費。
1自訂字型
說到字型,我們不難聯想到我們使用office時可以選擇的各種字型,我們就是需要這種字型檔,值得一提的是,Windows提供了很多字型檔,可以在C:\Windows\Fonts找到。當然,我們也可以去網路上下載你喜歡的字型檔。字型檔是ttf格式的喲。
那我們現在就開始,我們先把要使用的字型檔放入到工具中,操作如下:
(1)建立一個名叫assets的檔案夾,然後把字型檔複製到裡面
STXINGKA.TTF就是字型檔
(2)我們建立一個類,名叫FontCustom,寫入代碼:
public class FontCustom { // fongUrl是自訂字型分類的名稱 private static String fongUrl = "STXINGKA.TTF"; //Typeface是字型,這裡我們建立一個對象 private static Typeface tf; /** * 設定字型 */ public static Typeface setFont(Context context) { if (tf == null) { //給它設定你傳入的自訂字型檔,再返回回來 tf = Typeface.createFromAsset(context.getAssets(),fongUrl); } return tf; }}
(3)建立一個類名叫MyTextView繼承TextView,重寫2個參數的構造方法
public class MyTextView extends TextView { public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } /** * 初始化字型 * @param context */ private void init(Context context) { //設定字型樣式 setTypeface(FontCustom.setFont(context)); }}
2使用自訂字型類
我們複製MyTextView的路徑到activity_main中,替換原有的TextView,我這裡的路徑是
com.example.fengjun.fontdiy.MyTextView
修改activity_main中的代碼:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.fengjun.fontdiy.MainActivity"> <com.example.fengjun.fontdiy.MyTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:layout_centerInParent="true" android:text="Hello!我是自訂字型" /></RelativeLayout>
效果很酷炫,對不對?我們只需要2個類就可以完成了自訂字型,之後再哪裡需要使用自訂字型,就把路徑替換原有的TextView就完成了!
3總結
自訂字型在我們的程式中其實用的地方不多,大多數時候,我們都喜歡用圖片來代替TextView來作為標題名稱等特殊地方。如果我們在程式中展示的文字內容,使用自訂字型,那就是非常棒的選擇,會給人一種耳目一新的感覺。
項目:http://pan.baidu.com/s/1pLhKgbh
Android中快速實現自訂字型!