android 自定义文字字体

@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"
    />

猜你喜欢

转载自blog.csdn.net/qq_28674511/article/details/81537085