android自定義TextView字體

修改 TextViw 爲自定義字體

最簡便的方法:

  1. 下載對應字體的 .ttf 的字體文件
    • 例如 : http://www.downcc.com/font/360567.html 下載 DIN Condensed Bold.woff.ttf 字體壓縮包 ;
    • 解壓即可看到 .ttf 的文件 ;
  2. 項目 src -> main目錄下 new -> dictionary 創建路徑 assets/fonts , 把 ttf 文件複製進去
  3. 使用
    TextView tv = (TextView)findViewById(R.id.my_textview);
    Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "fonts/DIN Condensed Bold.ttf");
    tv.setTypeface(typeface );
    

簡單封裝一下使它直接可以在xml文件中使用自定義字體

  1. 同上1 ;
  2. 同上2 ;
  3. 封裝一個 TextView 工具類
    package xxx.xxx.xxx.xxx;
    
    import android.content.Context;
    import android.graphics.Typeface;
    import android.support.annotation.Nullable;
    import android.support.v7.widget.AppCompatTextView;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    import xxx.xxx.xxx.xxx.application.MyApp;
    
    /**
     * DinCondensedBold 字體
     */
    public class TextViewDinCondensedBold extends AppCompatTextView {
    
        Typeface tfDinConBold = Typeface.createFromAsset(MyApp.sContext.getAssets(), "fonts/DINCondensedBold.ttf");
    
        public TextViewDinCondensedBold(Context context) {
            super(context);
            setTypeface(tfDinConBold);
        }
    
        public TextViewDinCondensedBold(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            setTypeface(tfDinConBold);
        }
    
        public TextViewDinCondensedBold(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            setTypeface(tfDinConBold);
        }
    }
    
  4. xml 中直接使用 :
    <com.xxx.xxx.xxx.xxx.TextViewDinCondensedBold
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="哈哈哈123"
        android:textSize="15dp" />
    
  5. 運行 , 完成 .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章