我有自己的字体,我想在所有版面中使用我的应用,我想更改我的应用的默认字体。
在styles.xml中我可以使用
<item name="android:fontFamily"></item>
更改字体更改,但如何在此处使用自定义字体?
在 App - &gt; src - &gt;主要,我创建了一个名为Assets 的新目录,然后是另一个名为Fonts 的目录,这就是我放置自定义字体的位置。
这可能吗?如果是这样,怎么样?
修改
正如mayosk所说,我添加了
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
制作了一个扩展Application的Java类,如下所示
public class CustomResources extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/din_light.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
}
但字体仍然相同,我错过了什么
答案 0 :(得分:1)
使用书法: https://github.com/chrisjenx/Calligraphy
为您的app build.gradle添加依赖项:
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
并将您的应用程序类扩展到需要将此代码添加到onCreate方法
的位置CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("Fonts/customFont.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
并且您还需要在活动中覆盖attachBaseContext方法():
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
答案 1 :(得分:0)
首先,你需要创建一个扩展 Textview 的基类,这里是基类
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTypeFace(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeFace(context);
}
public MyTextView(Context context) {
super(context);
setTypeFace(context);
}
private void setTypeFace(Context context) {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Bold.ttf"));
}}
稍后在xml中
<com.example.MyTextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="hi" />
同样适用于edittext。通过这样做,所有textviews和edittexts都在整个应用程序中使用相同的字体。
答案 2 :(得分:0)
我有一种更改默认字体的特殊方法。我设置了一个完整的画颜来创建自定义视图并在 onDraw 方法上绘制字体,而不是xml方式。 像这样:
`private void initPaint(Context context)
{
mTextPaint = new TextPaint();
mTextPaint.setTextSize(66.46F);
mTextPaint.setColor(Color.BLACK);
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/MFKeKe_Noncommercial-Regular.ttf");
mTextPaint.setTypeface(typeface);
mTextPaint.setTextSkewX(-0.5F);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
mStaticLayout = new StaticLayout(TEXT1,mTextPaint,canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL,1.0F,0.0F,false);
mStaticLayout.draw(canvas);
canvas.restore();
}`
但通常情况下, 对于任何仍有疑问的人,真正的,好的答案就在这里: