Android 字体库详解
16lz
2021-01-23
android 自带的有字体库,在xml中可以设置,当然代码中自不必说。
1:xml使用
使用的是typeface这个属性,android中自带提供给我们的只有四种:
normal,sans,monospace,serif。
下面分别是对应的效果
2:代码实现
Typeface.create(String familyName, int style);
创建一个给定名字和指定样式的字体实例
Typeface.create(Typeface family, int style);
创建与指定的现有字体最匹配的字体对象
Typeface.createFromAsset(AssetManager mgr, String path)
从指定的字体数据创建一个新的字体。
Typeface.createFromFile(@Nullable File file) Typeface.createFromFile(String path)
根据文件或者路径创建新的字体。
3:自定义样式的textview
另外附上简单的自定义textview用来实现assets下字体的:
public class CommonTextView extends AppCompatTextView { private int typefaceStr; private Context context; public CommonTextView(Context context) { this(context, null); } public CommonTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CommonTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; init(context, attrs, defStyleAttr); } public void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CommonTextView, defStyleAttr, 0); if (typedArray != null) typefaceStr = typedArray.getInt(R.styleable.CommonTextView_typeface, MEDIUM); typedArray.recycle(); setTypefaceStr(); } public void setTypefaceStr() { Typeface typeFace; if (typefaceStr == BOLD) { typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Bold.ttf"); setTypeface(typeFace); } else if (typefaceStr == MEDIUM) { typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Medium.ttf"); setTypeface(typeFace); } else if (typefaceStr == HEAVY) { typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Heavy.ttf"); setTypeface(typeFace); } else if (typefaceStr == LIGHT) { typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Light.ttf"); setTypeface(typeFace); } else if (typefaceStr == BOOK) { typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Book.ttf"); setTypeface(typeFace); } else { } } class TypeFaceEnum { static final int BOLD = 0; static final int MEDIUM = 1; static final int HEAVY = 2; static final int BOOK = 3; static final int LIGHT = 4; static final int NORMAL = 5; }}
attrs样式如下:
最后是使用方式:
更多相关文章
- Android中通过typeface设置字体
- android基础--TextView详解
- android DatePicker样式设置
- Android引用ttf图标字体库
- iphone开发之常用控件的使用详解
- Android中字体颜色的设置