天天看點

Android 設定字型的三種方法(TypeFace)

Android系統預設字型支援四種字型,分别為:

  1. noraml (普通字型,系統預設使用的字型)
  2. sans(非襯線字型)
  3. serif (襯線字型)
  4. monospace(等寬字型)

除此之外還可以使用其他字型檔案(*.ttf)

一、使用系統自帶的字型

1.在xml中修改字型

<!--  不指明typeface -->
            <TextView style="@style/TextStyle"
                android:text="Hello , world  中華人民共和國(沒有設定屬性)"/>

            <!--  使用預設的normal字型-->
            <TextView
                style="@style/TextStyle"
                android:type
                android:text="Hello , world  中華人民共和國(xml設定normal)"/>

            <!--  使用預設的sans字型-->
            <TextView
                style="@style/TextStyle"
                android:type
                android:text="Hello , world  中華人民共和國(xml設定sans)"/>

            <!--  使用預設的serifs字型-->
            <TextView
                style="@style/TextStyle"
                android:type
                android:text="Hello , world  中華人民共和國(xml設定serif)"/>

            <!--  使用預設的monospace字型-->
            <TextView
                style="@style/TextStyle"
                android:type
                android:text="Hello , world  中華人民共和國(xml設定monospace)"/>
           

2.在Java代碼中修改字型

vSansText = (TextView) findViewById(R.id.sans);
        vSerifText = (TextView) findViewById(R.id.serif);
        vMonospaceText = (TextView) findViewById(R.id.monospace);

        //設定字型樣式
        vSansText.setTypeface(Typeface.SANS_SERIF);
        vSerifText.setTypeface(Typeface.SERIF);
        vMonospaceText.setTypeface(Typeface.MONOSPACE);
           

二、在Android中可以引入其他字型

Android 設定字型的三種方法(TypeFace)
//從asset 讀取字型
        //得到AssetManager
        AssetManager mgr = getAssets();
        //根據路徑得到Typeface
        Typeface tf = Typeface.createFromAsset(mgr, "fonts/HelveticaNeueLTPro-UltLt.otf");
        //設定字型
        vTTFText.setTypeface(tf);
           

源碼

繼續閱讀