アプリケーション全体で特定のフォントを使用する必要があります。同じための.ttfファイルがあります。これをデフォルトのフォントとして設定し、アプリケーションの起動時にアプリケーションの他の場所で使用することはできますか?設定すると、レイアウトXMLでどのように使用できますか?
25 に答える
はい、反射で。これは機能します(この回答に基づいて):
(注: これはカスタム フォントがサポートされていないための回避策です。この状況を変更したい場合は、ここで Android の問題に星を付けて賛成票を投じてください)。注:その問題について「私も」コメントを残さないでください。コメントを残すと、その問題を見つめたすべての人にメールが届きます。ですから、「スター」をつけてください。
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
次に、アプリケーションクラスなどで、いくつかのデフォルト フォントをオーバーロードする必要があります。
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
もちろん、同じフォント ファイルを使用している場合は、これを改善して一度だけ読み込むようにすることもできます。
"MONOSPACE"ただし、たとえばをオーバーライドしてから、そのフォント書体アプリケーション全体に適用するスタイルを設定する傾向があります。
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
API 21 Android 5.0
機能しないというコメントのレポートを調査し、テーマと互換性がないようandroid:Theme.Material.Lightです。
そのテーマが重要でない場合は、古いテーマを使用してください。
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>
Android にはカスタム フォント用の優れたライブラリがあります: Calligraphy
ここにそれを使用する方法のサンプルがあります。
Gradle では、次の行をアプリの build.gradle ファイルに入れる必要があります。
dependencies {
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
}
Application次に、このコードを拡張して記述するクラスを作成します。
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("your font path")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
}
アクティビティ クラスでは、このメソッドを onCreate の前に置きます。
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
最後に、マニフェスト ファイルは次のようになります。
<application
.
.
.
android:name=".App">
アクティビティ全体がフォントに変更されます。シンプルでクリーンです!
これはアプリケーション全体では機能しませんが、アクティビティでは機能し、他のアクティビティで再利用できます。@FR073N のおかげで、他のビューをサポートするためにコードを更新しました。Buttons、などの問題についてはわかりませんRadioGroups。これらのクラスはすべて拡張されているため、問題なくTextView動作するはずです。リフレクションを使用するためのブール条件を追加しました。
注: 指摘されているように、これは動的コンテンツでは機能しません! onCreateViewそのために、このメソッドをorメソッドで呼び出すことは可能getViewですが、追加の作業が必要です。
/**
* Recursively sets a {@link Typeface} to all
* {@link TextView}s in a {@link ViewGroup}.
*/
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect)
{
if (mContainer == null || mFont == null) return;
final int mCount = mContainer.getChildCount();
// Loop through all of the children.
for (int i = 0; i < mCount; ++i)
{
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView)
{
// Set the font if it is a TextView.
((TextView) mChild).setTypeface(mFont);
}
else if (mChild instanceof ViewGroup)
{
// Recursively attempt another ViewGroup.
setAppFont((ViewGroup) mChild, mFont);
}
else if (reflect)
{
try {
Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
mSetTypeface.invoke(mChild, mFont);
} catch (Exception e) { /* Do something... */ }
}
}
}
次に、それを使用するには、次のようにします。
final Typeface mFont = Typeface.createFromAsset(getAssets(),
"fonts/MyFont.ttf");
final ViewGroup mContainer = (ViewGroup) findViewById(
android.R.id.content).getRootView();
HomeActivity.setAppFont(mContainer, mFont);
それが役立つことを願っています。
要約すれば:
オプション#1: リフレクションを使用してフォントを適用します(westonとRoger Huangの回答を組み合わせます):
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,final Typeface newTypeface) {
if (isVersionGreaterOrEqualToLollipop()) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("sans-serif", newTypeface);
try {
final Field staticField = Typeface.class.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
アプリケーション クラスでの使用法:
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
そのフォント書体アプリケーション全体を強制するスタイルを設定します ( lovefishに基づく):
ロリポップ前:
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
ロリポップ (API 21):
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textAppearance">@style/CustomTextAppearance</item>
</style>
<style name="CustomTextAppearance">
<item name="android:typeface">monospace</item>
</style>
</resources>
オプション 2: フォントをカスタマイズする必要があるすべてのビューをサブクラス化します。ListView、EditTextView、Button など ( Palaniの回答):
public class CustomFontView extends TextView {
public CustomFontView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomFontView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomFontView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
オプション 3: 現在の画面のビュー階層をトラバースするビュー クローラーを実装します。
バリエーション#1(トムの答え):
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect)
{
if (mContainer == null || mFont == null) return;
final int mCount = mContainer.getChildCount();
// Loop through all of the children.
for (int i = 0; i < mCount; ++i)
{
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView)
{
// Set the font if it is a TextView.
((TextView) mChild).setTypeface(mFont);
}
else if (mChild instanceof ViewGroup)
{
// Recursively attempt another ViewGroup.
setAppFont((ViewGroup) mChild, mFont);
}
else if (reflect)
{
try {
Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
mSetTypeface.invoke(mChild, mFont);
} catch (Exception e) { /* Do something... */ }
}
}
}
使用法 :
final ViewGroup mContainer = (ViewGroup) findViewById(
android.R.id.content).getRootView();
HomeActivity.setAppFont(mContainer, Typeface.createFromAsset(getAssets(),
"fonts/MyFont.ttf"));
バリエーション #2: https://coderwall.com/p/qxxmaa/android-use-a-custom-font-everywhere。
オプション #4: Calligraphy というサードパーティのライブラリを使用します。
個人的には、オプション 4 をお勧めします。
API 21 Android 5.0 に対するWestonの回答を改善したいと思います。
原因
API 21 では、ほとんどのテキスト スタイルに次のような fontFamily 設定が含まれています。
<style name="TextAppearance.Material">
<item name="fontFamily">@string/font_family_body_1_material</item>
</style>
デフォルトの Roboto Regular フォントを適用します。
<string name="font_family_body_1_material">sans-serif</string>
android:fontFamily は android:typeface 属性 (参照)よりも優先度が高いため、元の回答はモノスペース フォントの適用に失敗します。内部に android:fontFamily 設定がないため、Theme.Holo.* を使用することは有効な回避策です。
解決
Android 5.0 ではシステム書体が静的変数 Typeface.sSystemFontMap (参照) に配置されているため、同じリフレクション手法を使用してそれを置き換えることができます。
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
if (isVersionGreaterOrEqualToLollipop()) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("sans-serif", newTypeface);
try {
final Field staticField = Typeface.class
.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
それは非常に簡単です... 1.カスタムフォントをダウンロードしてアセットに入れます..次に、テキストビュー用に別のクラスを次のように記述します。ここでは、futuraフォントを使用しました
public class CusFntTextView extends TextView {
public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CusFntTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CusFntTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
}
xml で次の操作を行います。
<com.packagename.CusFntTextView
android:id="@+id/tvtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi Android"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
TextViewやその他のコントロールを拡張することもお勧めしますが、コンストラクトにフォントを設定することを検討したほうがよいでしょう。
public FontTextView(Context context) {
super(context);
init();
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
protected void init() {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), AppConst.FONT));
}
「 Theme.AppCompat 」をテーマにしたAPI 21以上のAndroid lollipopに対するwestonとRoger Huangの回答を改善したいと思います。
Android 4.4以下
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
以上 (等しい) API 5.0
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textAppearance">@style/CustomTextAppearance</item>
</style>
<style name="CustomTextAppearance">
<item name="android:typeface">monospace</item>
</style>
</resources>
FontsOverride util ファイルは、 westonの回答と同じです。私はこれらの電話でテストしました:
Nexus 5 (Android 5.1 プライマリ Android システム)
ZTE V5 (アンドロイド 5.1 CM12.1)
XIAOMI ノート (android 4.4 MIUI6)
HUAWEI C8850(android 2.3.5 不明)
すべてのレイアウトにカスタム フォントを 1 つずつ設定できます。ルートの View.First を渡すことで、すべてのレイアウトから関数を 1 回呼び出すだけで、このようなフォント オブジェクトにアクセスするためのシングルトン アプローチを作成できます。
public class Font {
private static Font font;
public Typeface ROBO_LIGHT;
private Font() {
}
public static Font getInstance(Context context) {
if (font == null) {
font = new Font();
font.init(context);
}
return font;
}
public void init(Context context) {
ROBO_LIGHT = Typeface.createFromAsset(context.getAssets(),
"Roboto-Light.ttf");
}
}
上記のクラスでさまざまなフォントを定義できます。次に、フォントを適用するフォント ヘルパー クラスを定義します。
public class FontHelper {
private static Font font;
public static void applyFont(View parentView, Context context) {
font = Font.getInstance(context);
apply((ViewGroup)parentView);
}
private static void apply(ViewGroup parentView) {
for (int i = 0; i < parentView.getChildCount(); i++) {
View view = parentView.getChildAt(i);
//You can add any view element here on which you want to apply font
if (view instanceof EditText) {
((EditText) view).setTypeface(font.ROBO_LIGHT);
}
if (view instanceof TextView) {
((TextView) view).setTypeface(font.ROBO_LIGHT);
}
else if (view instanceof ViewGroup
&& ((ViewGroup) view).getChildCount() > 0) {
apply((ViewGroup) view);
}
}
}
}
上記のコードでは、textView と EditText のみにフォントを適用しています。他のビュー要素にも同様にフォントを適用できます。ルート ビュー グループの ID を上記の apply font メソッドに渡すだけです。たとえば、レイアウトは次のとおりです。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/mainParent"
tools:context="${relativePackage}.${activityClass}" >
<RelativeLayout
android:id="@+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/homeFooter"
android:layout_below="@+id/edit" >
<ImageView
android:id="@+id/PreviewImg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/abc_list_longpressed_holo"
android:visibility="gone" />
<RelativeLayout
android:id="@+id/visibilityLayer"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/UseCamera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/camera" />
<TextView
android:id="@+id/tvOR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/UseCamera"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="OR"
android:textSize="30dp" />
<TextView
android:id="@+id/tvAND"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="OR"
android:textSize="30dp" />
</RelativeLayout>
上記のレイアウトでは、ルートの親 ID は「メインの親」であり、フォントを適用できるようになりました
public class MainActivity extends BaseFragmentActivity {
private EditText etName;
private EditText etPassword;
private TextView tvTitle;
public static boolean isHome = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Font font=Font.getInstance(getApplicationContext());
FontHelper.applyFont(findViewById(R.id.mainParent), getApplicationContext());
}
}
乾杯 :)
TextViewを拡張し、XMLレイアウト内またはTextViewが必要な場所で常にカスタムTextViewを使用することをお勧めします。カスタムTextViewで、オーバーライドしますsetTypeface
@Override
public void setTypeface(Typeface tf, int style) {
//to handle bold, you could also handle italic or other styles here as well
if (style == 1){
tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "MuseoSans700.otf");
}else{
tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "MuseoSans500.otf");
}
super.setTypeface(tf, 0);
}
トムのソリューションはうまく機能しますが、TextView と EditText でしか機能しません。
ほとんどのビュー (RadioGroup、TextView、Checkbox など) をカバーしたい場合は、それを行うメソッドを作成しました。
protected void changeChildrenFont(ViewGroup v, Typeface font){
for(int i = 0; i < v.getChildCount(); i++){
// For the ViewGroup, we'll have to use recursivity
if(v.getChildAt(i) instanceof ViewGroup){
changeChildrenFont((ViewGroup) v.getChildAt(i), font);
}
else{
try {
Object[] nullArgs = null;
//Test wether setTypeface and getTypeface methods exists
Method methodTypeFace = v.getChildAt(i).getClass().getMethod("setTypeface", new Class[] {Typeface.class, Integer.TYPE});
//With getTypefaca we'll get back the style (Bold, Italic...) set in XML
Method methodGetTypeFace = v.getChildAt(i).getClass().getMethod("getTypeface", new Class[] {});
Typeface typeFace = ((Typeface)methodGetTypeFace.invoke(v.getChildAt(i), nullArgs));
//Invoke the method and apply the new font with the defined style to the view if the method exists (textview,...)
methodTypeFace.invoke(v.getChildAt(i), new Object[] {font, typeFace == null ? 0 : typeFace.getStyle()});
}
//Will catch the view with no such methods (listview...)
catch (Exception e) {
e.printStackTrace();
}
}
}
}
このメソッドは、XML で設定されたビューのスタイル (ボールド、イタリックなど) を取得し、存在する場合はそれらを適用します。
ListView の場合は、常にアダプターを作成し、getView 内でフォントを設定します。
現在のビュー階層のビューに書体を割り当てるクラスを作成し、現在の書体プロパティ (太字、標準、必要に応じて他のスタイルを追加できます) に基づいています。
public final class TypefaceAssigner {
public final Typeface DEFAULT;
public final Typeface DEFAULT_BOLD;
@Inject
public TypefaceAssigner(AssetManager assetManager) {
DEFAULT = Typeface.createFromAsset(assetManager, "TradeGothicLTCom.ttf");
DEFAULT_BOLD = Typeface.createFromAsset(assetManager, "TradeGothicLTCom-Bd2.ttf");
}
public void assignTypeface(View v) {
if (v instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) v).getChildCount(); i++) {
View view = ((ViewGroup) v).getChildAt(i);
if (view instanceof ViewGroup) {
setTypeface(view);
} else {
setTypeface(view);
}
}
} else {
setTypeface(v);
}
}
private void setTypeface(View view) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
Typeface typeface = textView.getTypeface();
if (typeface != null && typeface.isBold()) {
textView.setTypeface(DEFAULT_BOLD);
} else {
textView.setTypeface(DEFAULT);
}
}
}
}
onViewCreated または onCreateView のすべてのフラグメント、onCreate のすべてのアクティビティ、および getView または newView のすべてのビュー アダプターで、以下を呼び出します。
typefaceAssigner.assignTypeface(view);
build.gradle 3.0.0以降のapi 26では、resにフォントディレクトリを作成し、この行をスタイルで使用できます
<item name="android:fontFamily">@font/your_font</item>
build.gradle を変更するには、build.gradle の依存関係でこれを使用します
classpath 'com.android.tools.build:gradle:3.0.0'
また、API 21 Android 5.0 に対する Weston の回答を改善したいと思います。
DEFAULT フォントを使用している場合、Samsung s5 でも同じ問題が発生しました。(他のフォントでは問題なく動作しています)
TextviewまたはButtonごとに、XMLファイルで書体(たとえば「sans」)を設定することで、なんとか機能させることができました
<TextView
android:layout_width="match_parent"
android:layout_height="39dp"
android:textColor="@color/abs__background_holo_light"
android:textSize="12sp"
android:gravity="bottom|center"
android:typeface="sans" />
および MyApplication クラス :
public class MyApplication extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SANS_SERIF",
"fonts/my_font.ttf");
}
}
それが役に立てば幸い。
はい、アプリケーション全体にフォントを設定できます。
これを実現する最も簡単な方法は、目的のフォントをアプリケーションにパッケージ化することです。
これを行うには、プロジェクト ルートにassets/ フォルダーを作成し、フォント (TrueType または TTF 形式) をアセットに配置します。
たとえば、assets/fonts/ を作成し、そこに TTF ファイルを配置できます。
public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}