安卓自定義字體設置框架——calligraphy

1.少量字體簡單做法

下載字體文件.ttf,在項目main下面新建assets文件,將字體包導入,
在這裏插入圖片描述
然後在Activity中,調用,如下

 Button button=findViewById(R.id.btn_handin);
//        AssetManager assets = getAssets();//獲取assets目錄
//        TextView textView1=findViewById(R.id.text_write);
//        TextView textView = findViewById(R.id.text_type);
//        Typeface fromAsset = Typeface.createFromAsset(assets, "boYangXingShu7000-1.ttf");//typeface字體文件
//        button.setTypeface(fromAsset);
//        textView1.setTypeface(fromAsset);
//        textView.setTypeface(fromAsset);//設置字體類型

但是當我們需要改很多控件字體的時候,上面的方法就不太實用了,下面有更簡單的方法
1.在grade文件下的dependencies中加入

//批量字體添加
    implementation'uk.co.chrisjenx:calligraphy:2.2.0'
    配置依賴路徑,引入開源字體設置

2。在自定義的application的oncreate進行設置

 CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
        .setDefaultFontPath("boYangXingShu7000-1.ttf")
        .setFontAttrId(R.attr.fontPath)
        .build());

然後重寫attachBaseContext方法,

   @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

最後就可以在佈局文件中使用了,

<TextView
            android:id="@+id/text_type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:text="看看你適合的type"
            fontPath="boYangXingShu7000-1.ttf"
            android:textSize="25dp"
            tools:ignore="MissingPrefix" />//因爲上面的fontPath不識別,所以加這一行忽略前綴就好了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章