【发布时间】:2015-08-17 22:14:54
【问题描述】:
我正在开发一个 android 项目,我想更改所有应用程序的默认字体,而不仅仅是单个 TextView 或按钮。
我的自定义字体存储为assets/fonts/font.ttf
【问题讨论】:
我正在开发一个 android 项目,我想更改所有应用程序的默认字体,而不仅仅是单个 TextView 或按钮。
我的自定义字体存储为assets/fonts/font.ttf
【问题讨论】:
使用书法库!它完全是为这个问题而设计的。
https://github.com/chrisjenx/Calligraphy
来自文档:
在扩展Application 的类中放置此代码。
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/font.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
然后在每个Activity
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
【讨论】:
你所要做的就是:首先创建这样的字体对象:
Typeface typeFace= Typeface.createFromAsset(getAssets(),
"fonts/font.ttf");
并在需要的地方设置此字体,例如:
textView.setTypeFace(typeFace);
您无法通过将字体文件放入资产中来更改整个应用程序的字体。
【讨论】:
我以前不得不处理这个问题。这很烦人,因为没有好的方法。我发现它的最好方法是覆盖 textview 并改用该自定义类。做这门课
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by shemesht on 6/3/15.
*/
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
Typeface typeFace= Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
setTypeface(typeFace);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface typeFace= Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
setTypeface(typeFace);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Typeface typeFace= Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
setTypeface(typeFace);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
Typeface typeFace= Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
setTypeface(typeFace);
}
}
然后在你的xml中放
<com.yourApp.Namehere.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this text has a new font!"/>
就是这样。你仍然可以在你的java中正常引用你的textview
【讨论】: