Java 在Android中使用自定义字体
我使用的是abeakrg.TTF字体。与其他教程一样,我将其放在资源/字体中 我用了这个密码Java 在Android中使用自定义字体,java,android,fonts,custom-font,Java,Android,Fonts,Custom Font,我使用的是abeakrg.TTF字体。与其他教程一样,我将其放在资源/字体中 我用了这个密码 public class Typefaces { private static final String TAG = "Typefaces"; private final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>(); public Typeface get(
public class Typefaces {
private static final String TAG = "Typefaces";
private final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/abeakrg.TTF");
cache.put(assetPath, tf);
TextView tv3 = (TextView) findViewById(R.id.txt1);
tv3.setTypeface(tf);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
但是当我在模拟器或设备中运行它时,字体不会出现。因此,我可以知道我所犯的错误以及如何解决这个问题。您可以从Textview类和settypeface中创建一个子类,如下所示,并在xml中使用
public class MyTextView extends TextView {
public MyTextView (Context context) {
super(context);
if (!isInEditMode())
init(context);
}
private void init(Context context) {
setTypeface(Utils.getTypeface(context));
}
public MyTextView (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode())
init(context);
}
public MyTextView (Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode())
init(context);
}
}
public class Utils {
private static Typeface tf;
public static Typeface getTypeface(Context ctx) {
if (tf == null) {
tf = Typeface.createFromAsset(ctx.getAssets(),
"fonts/HelveticaNeue.ttf");
}
return tf;
}
public static Typeface getDolphinTypeface(Context ctx) {
return Typeface.createFromAsset(ctx.getAssets(), "fonts/GOTHIC.TTF");
}
}
你可以用字体写
例如:如果我有xyz_font.ttf样式,那么我会这样设置它
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/xyz_font.ttf");
txt.setTypeface(font);
您需要将xyz_font.ttf文件放在assets/fonts文件夹中,而不是res文件夹中。请参阅此自定义TextView类
步骤1:
创建一个类CustomTextView
步骤3:将所需字体复制到项目的资产文件夹中
步骤4:在布局中使用CustomTextView.java代替TextView。您可以在“自定义视图”部分的XML布局编辑器中找到CustomTextView
像这样使用自定义文本视图
<com.your.path.CustomTextView
android:id="@+id/custom_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="custom font"
app:typeface="your_font.ttf" />
@SimplePlan我使用了它,它给出了一个错误,说在你的上下文对象是c之前,上下文不能被解析,所以像c.getAssets一样尝试;
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="typeface" format="string" />
</declare-styleable>
</resources>
<com.your.path.CustomTextView
android:id="@+id/custom_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="custom font"
app:typeface="your_font.ttf" />