Android中自定义textview可以进行自体设置

废话不说,下面是代码:

    `public class FontTextView extends TextView {

    private Context mContext;

    private String TypefaceName = "";

    public String getTypefaceName() {

        return TypefaceName;

    }

    public void setTypefaceName(String typefaceName) {

        TypefaceName = typefaceName;

        Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "font/" + TypefaceName + ".ttf");

        this.setTypeface(typeface);

        System.gc();

    }

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);

        this.mContext = context;

        int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);

        if (resouceId != 0) {

            TypefaceName = context.getResources().getString(resouceId);

        } else {

            TypefaceName = attrs.getAttributeValue(null, "typefaceName");

        }

        if (TypefaceName != null && !"".equals(TypefaceName)) {

            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf");

            this.setTypeface(typeface);

        }

    }

    public FontTextView(Context context, AttributeSet attrs) {

        super(context, attrs);

        this.mContext = context; // 先判断是否配置的资源文件

        int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);

        if (resouceId != 0) {

            TypefaceName = context.getResources().getString(resouceId);

        } else {

            TypefaceName = attrs.getAttributeValue(null, "typefaceName");

        }

        if (TypefaceName != null && !"".equals(TypefaceName)) {

            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf");

            this.setTypeface(typeface);

        }

    }

    public FontTextView(Context context) {

        super(context);

        this.mContext = context;

    }

    }`

下面是布局:大字体是要设置的属性,pop是字体库的名字

注意:自体库文件我这里放到了assets中的font文件夹中给个截图吧:

strings.xml文件中的截图:可以把字体的配置放到字符串资源中,这样就能统一进行更改了,如果你的需要中要动态的进行配置的话,可以对FontTextView进行改写,我的想法是在将自体配置放进prefrence中进行配置,这样就可以直接在FontTextView中进行改写了,本来想把这个类写的完成呢,由于时间关系就没写,有需求的可以自己去实现。就说这么多吧。

你可能感兴趣的:(Android中自定义textview可以进行自体设置)