我有自己的字体,我想在所有布局中用于我的应用程序,我想更改应用程序的默认字体。
在样式中.xml我可以使用
<item name="android:fontFamily"></item>
更改更改字体,但如何在此处使用我的自定义字体?
在 App -> src -> main 中,我创建了一个名为 Assets 的新目录,然后在该目录中创建了一个名为 Fonts 的目录,这是我放置自定义字体的地方。
这可能吗?如果是这样,如何?
编辑
正如马约斯克所说,我补充说
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
并制作了一个扩展应用程序的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()
);
}
}
但是字体还是一样,我错过了什么吗
使用书法:https://github.com/chrisjenx/Calligraphy
将依赖项添加到您的应用程序构建.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 method((:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
<</div>
div class="one_answers"> 首先,您需要创建一个扩展 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" />
编辑文本也一样。通过这样做,所有文本视图和编辑文本在整个应用程序中都具有相同的字体。
我有一种特殊的方式来更改默认字体。我在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();
}`
但通常,对于仍有疑问的人,真正的好答案在这里:
https://stackoverflow.com/a/16883281/1154026