0
什麼是最簡單和最快的方式來改變字體android項目,我想避免改變每一個視圖。爲所有的android項目添加默認的ttf字體
什麼是最簡單和最快的方式來改變字體android項目,我想避免改變每一個視圖。爲所有的android項目添加默認的ttf字體
您可以爲所有視圖製作自定義視圖。
例如,爲TextView的:通過使用這個天秤座
<PackageName.MyTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello" />
:
public class MyTextView extends TextView {
private Typeface typeface;
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.app);
String customFont = a.getString(R.styleable.app_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
private boolean setCustomFont(Context ctx, String asset) {
try {
if (typeface == null) {
typeface = Typeface.createFromAsset(ctx.getAssets(),
getResources().getString(R.string.app_font1));
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
setTypeface(typeface);
return true;
}
}
在String.xml
添加此標籤 -
<string name="app_font1">fonts/Roboto-Regular.ttf</string>
在XML文件RY你不需要改變每一個視圖,只需創建一個自定義Activity
類,並重寫此方法:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
,然後擴展所有的活動與這一活動。
可能重複[是否可以爲整個應用程序設置字體?](http://stackoverflow.com/questions/2711858/is-it-possible-to-set-font-for-entire-application) – Fllo
以上鍊接的可能重複 –