android 自定義文字字型
阿新 • • 發佈:2018-11-09
@SuppressLint("AppCompatCustomView") public class TypefaceTextView extends TextView { //字型檔案放在assets檔案中 // fongUrl是自定義字型分類的名稱 private static String fongRegularUrl = "DIN-Regular.otf";//字型淺色 private static String fongMediumUrl = "DIN-Medium.otf";//字型粗色 //Typeface是字型,這裡我們建立一個物件 private Typeface tf; public TypefaceTextView(Context context) { super(context); init(context,1);//預設字型為1,regular } public TypefaceTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initType(context,attrs); } public TypefaceTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initType(context,attrs); } @SuppressLint("NewApi") public TypefaceTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initType(context,attrs); } private void initType(Context context,AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TypefaceView); int type=ta.getInt(R.styleable.TypefaceView_texttypeface,1); init(context,type); } /** * 初始化字型 * @param context */ private void init(Context context,int type) { //設定字型樣式 setTypeface(setFont(context,type)); } /** * 設定字型 */ public Typeface setFont(Context context,int type) { if (tf == null) { //給它設定你傳入的自定義字型檔案,再返回回來 if (type==1) {//自定義字型淺色 tf = Typeface.createFromAsset(context.getAssets(), fongRegularUrl); }else if (type==2){//自定義字型粗色 tf = Typeface.createFromAsset(context.getAssets(), fongMediumUrl); } } return tf; } }
//attrs屬性
<declare-styleable name="TypefaceView"> <attr name="texttypeface" format="enum"> <enum name="Regular" value="1"/> <enum name="Medium" value="2"/> </attr> </declare-styleable>
//在xml中使用
<包名.TypefaceTextView android:id="@+id/textview_mymoney" android:layout_width="wrap_content" android:layout_height="44dp" android:layout_below="@+id/layout_money" android:layout_marginLeft="16dp" android:text="****" android:textColor="#ff2e3c4d" android:textSize="36sp" app:texttypeface="Medium" //字型得型別,看你有多少種 android:letterSpacing="-0.02" />