我总是使用两种字体,一种是普通字体,一种是粗体字体。因此,当您需要加粗时,只需更改字体即可。从来没有遇到过问题,您还可以创建自定义 textviewplus。
像这样的东西:
/res/values/attrs.xml
<resources>
<attr name="fontFamily" format="enum">
<enum name="helvetica" value="0"/>
<enum name="helvetica_bold" value="1"/>
</attr>
你的TextViewPlus:
public class TextViewPlus extends TextView{
private static final String TAG = "TextViewPlus";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
int customFont = a.getInt(R.styleable.TextViewPlus_fontFamily, -1);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, int font) {
Typeface tf = null;
try {
tf = Typefaces.get(ctx, font);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typefaces.get(ctx, asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
如何使用:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.myapp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.myapp.viewhelpers.TextViewPlus
app:fontFamily="helvetica"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fontFamily="helvetica"
android:text="helo world"/>