一个字体替换开源项目:https://github.com/chrisjenx/Calligraphy
干货:直接参考官方demo:
https://github.com/chrisjenx/Calligraphy/tree/master/CalligraphySample
快速集成步骤:
1、添加依赖:
dependencies { compile 'uk.co.chrisjenx:calligraphy:2.2.0' }
2.导入字体文件:
如:E:\yg\Desktop\weekDay\WeekDay\app\src\main\assets\fonts\STLITI.TTF
3.拷贝官方Demo CalligraphySample中文件:
CustomViewWithTypefaceSupport.class
TextField.class
4.配置:
1)如果想给整个App设置默认自定义字体,先这么干,否则可跳过:
public class App extends Application { @Override public void onCreate() { super.onCreate(); //给应用整体设置,可以不设置,仅仅在个别Activity中使用,重写attachBaseContext方法 CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Roboto-ThinItalic.ttf")//如果没有这种字体,则使用默认字体,不会崩溃 // .setDefaultFontPath("fonts/STLITI.TTF") .setFontAttrId(R.attr.fontPath) .addCustomViewWithSetTypeface(CustomViewWithTypefaceSupport.class) .addCustomStyle(TextField.class, R.attr.textFieldStyle) .build() ); } }
2)如果只需要给某个控件,如TextView设置字体,这么干:
/** * Activity中,重写下面方法,写到Base页面中较好 * @param newBase */ @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); }
3)布局文件中,这么干:
3.1)
xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingPrefix"
3.2)
<Button android:id="@+id/selectedDay1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_marginBottom="10dp" android:background="@drawable/selector_btn" android:text="查询" android:gravity="center" fontPath="fonts/STLITI.TTF" android:textSize="18sp" android:textColor="@color/textColor" />
结束。
查询按钮文字已改变: