1. 程式人生 > 程式設計 >淺析Android載入字型包及封裝的方法

淺析Android載入字型包及封裝的方法

TextView載入字型包

在 Android 中,若需要使得某個TextView載入字型包,使用以下方式即可:

 Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/Bold.otf");
  textView.setTypeface(typeFace);

至於字型包的位置:

淺析Android載入字型包及封裝的方法

通過以上方法,可以使得一個TextView載入某種字型包,但是,還有這種需求:

  • 部分TextView載入字型包
  • 每個TextView載入的字型包不一定一樣

這時,我們就需要稍微封裝下,將其封裝成一個自定義TextView類,若需要使用字型包,則載入該類,同時,可以根據xml

裡面的值,從而載入不同的字型包。

封裝

定義屬性值

首先,我們需要從xml裡面獲取值,因此,需要在attr中進行屬性值的定義:

淺析Android載入字型包及封裝的方法

<declare-styleable name="FontTextView">
  <attr name="fontType" format="enum">
   <enum name="bold" value="1" />
   <enum name="heavy" value="2" />
  </attr>
 </declare-styleable>

這裡我只定義了兩種屬性,大家可以根據需求進行增減。

建立自定義TextView

public class FontTextView extends AppCompatTextView {

 public FontTextView(Context context) {
  super(context);
 }
 public FontTextView(Context context,@Nullable AttributeSet attrs) {
  this(context,attrs,0);
 }
 public FontTextView(Context context,@Nullable AttributeSet attrs,int defStyleAttr) {
  super(context,defStyleAttr);
 }
}

獲取屬性值

//獲取引數
  TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.FontTextView,defStyleAttr,0);

  int fontType = a.getInt(R.styleable.FontTextView_fontType,1);

進行值判斷並載入不同的字型包

private final int BOLD = 1;
 private final int HEAVY = 2;
 
 String fontPath = null;
  switch (fontType) {
   case BOLD:
    fontPath = "fonts/Bold.otf";
    break;
   case HEAVY:
    fontPath = "fonts/Heavy.otf";
    break;
   default:
  }
  //設定字型
  if (!TextUtils.isEmpty(fontPath)) {
   Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(),fontPath);
   setTypeface(typeFace);
  }

全部原始碼

public class FontTextView extends AppCompatTextView {

 private final int BOLD = 1;

 private final int HEAVY = 2;

 public FontTextView(Context context) {
  super(context);
 }

 public FontTextView(Context context,0);
 }

 public FontTextView(Context context,defStyleAttr);

  //獲取引數
  TypedArray a = context.obtainStyledAttributes(attrs,1);

  String fontPath = null;
  switch (fontType) {
   case BOLD:
    fontPath = "fonts/Bold.otf";
    break;
   case HEAVY:
    fontPath = "fonts/Heavy.otf";
    break;
   default:
  }
  //設定字型
  if (!TextUtils.isEmpty(fontPath)) {
   Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(),fontPath);
   setTypeface(typeFace);

  }
 }
}

若需要使用字型包TextView,使用以下方式即可:

<com.jm.core.common.widget.textview.FontTextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:fontType="bold"
  android:text="測試" />

效果

淺析Android載入字型包及封裝的方法

到此這篇關於淺析Android載入字型包及封裝的方法的文章就介紹到這了,更多相關android載入字型包封裝內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!