36

アプリケーション全体でフォントを変更し、そのためのスタイルファイルを作成しようとしています。このファイル(下記)では、AndroidのTextAppearanceスタイルの書体の値を変更したいだけです。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="NightRiderFont" parent="@android:style/TextAppearance">
        <item name="android:typeface"> /***help need here***/ </item>
    </style>
</resources>

ただし、フォントは「assets /fonts/」にあります。このフォントにアクセスするにはどうすればよいですか。そのスタイルをテーマとして使用して、プログラムですべてのTextViewを手動で変更する必要がなくなります。

要約として:XMLで「アセットフォルダのファイル」にアクセスするにはどうすればよいですか?

4

14 に答える 14

78

私の研究では、xmlファイルに外部フォントを追加する方法はありません。xmlでは3つのデフォルトフォントのみが使用可能です

ただし、このコードを使用してJavaで使用できます。

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");  
textfield.setTypeface(tf,Typeface.BOLD);

アップデート:

ここで、TextViewを拡張するカスタムクラスを作成し、それをxmlファイルで使用することでこれを行う方法を見つけました。

public class TextViewWithFont extends TextView {
    private int defaultDimension = 0;
    private int TYPE_BOLD = 1;
    private int TYPE_ITALIC = 2;
    private int FONT_ARIAL = 1;
    private int FONT_OPEN_SANS = 2;
    private int fontType;
    private int fontName;

    public TextViewWithFont(Context context) {
        super(context);
        init(null, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }
    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.font, defStyle, 0);
        fontName = a.getInt(R.styleable.font_name, defaultDimension);
        fontType = a.getInt(R.styleable.font_type, defaultDimension);
        a.recycle();
        MyApplication application = (MyApplication ) getContext().getApplicationContext();
        if (fontName == FONT_ARIAL) {
            setFontType(application .getArialFont());
        } else if (fontName == FONT_OPEN_SANS) {
            setFontType(application .getOpenSans());
        }
    }
    private void setFontType(Typeface font) {
        if (fontType == TYPE_BOLD) {
            setTypeface(font, Typeface.BOLD);
        } else if (fontType == TYPE_ITALIC) {
            setTypeface(font, Typeface.ITALIC);
        } else {
            setTypeface(font);
        }
    }
}

とxmlで

<com.example.customwidgets.TextViewWithFont
        font:name="Arial"
        font:type="bold"
        android:layout_width="wrap_content"
        android:text="Hello world "
        android:padding="5dp"
        android:layout_height="wrap_content"/>

xmlのルートにスキーマを追加することを忘れないでください

xmlns:font="http://schemas.android.com/apk/res-auto"

そして、カスタム属性を保持しているディレクトリattrs.xml内にファイルを作成します。values

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="font">
        <attr name="type">
        <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
        </attr>
        <attr name="name">
            <enum name="Arial" value="1"/>
            <enum name="OpenSans" value="2"/>
        </attr>
    </declare-styleable>
</resources>

アップデート:

このカスタムビューをリストビューで使用すると、パフォーマンスの問題が見つかりました。これは、ビューが読み込まれるたびにフォントオブジェクトが作成されるためです。私が見つけた解決策は、アプリケーションクラスでフォントを初期化し、そのフォントオブジェクトを次のように参照することです。

MyApplication application = (MyApplication) getContext().getApplicationContext();

アプリケーションクラスは次のようになります

public class MyApplication extends Application {

    private Typeface arialFont, openSans;

    public void onCreate() {
        super.onCreate();

        arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL);
        openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS);
    }

    public Typeface getArialFont() {
        return arialFont;
    }

    public Typeface getOpenSans() {
        return openSans;
    }
}
于 2011-07-19T12:00:22.203 に答える
7

編集2:

最後に、フォントはxmlでサポートされています(サポートライブラリを介した下位互換性もあります):https ://developer.android.com/preview/features/fonts-in-xml.html


編集:

今は書道ライブラリを使っています。カスタムフォントの最も簡単な方法です。

あなたは何ができますか:

  • のカスタムフォントTextView
  • TextAppearanceのカスタムフォント
  • スタイルのカスタムフォント
  • テーマのカスタムフォント
  • FontSpannableは、テキストの一部にのみフォントを適用します

私はこれを行う別の方法を見つけました。

このチュートリアルTextViewを使用し て自分で作成する必要があります

それはそれほど難しいことではなく、この後、あなたはそれTextViewをあなた自身のフォントで使うことができます。

まだ誰かがこれを見ているかどうかはわかりませんが、役立つかもしれないと思いました。

于 2013-10-30T10:24:10.123 に答える
5

シングルフォントを使用している場合にこの機能を使用します。

public static void applyFont(final Context context, final View root, final String fontName) {
        try {
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                for (int i = 0; i < viewGroup.getChildCount(); i++)
                    applyFont(context, viewGroup.getChildAt(i), fontName);
            } else if (root instanceof TextView)
                ((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName));
        } catch (Exception e) {
            Log.e("ProjectName", String.format("Error occured when trying to apply %s font for %s view", fontName, root));
            e.printStackTrace();
        }
    }
于 2014-01-16T05:35:35.890 に答える
2

Sooryaは正しいですが、多くのtextViewに同じフォントを配置する必要がある場合は、必要な書体を返す静的メソッド内にそのコードを配置することをお勧めします。それはあなたのコードの行を減らします。または、Applicationを拡張するクラスを作成し、Typefaceを返すGETメソッドを作成することをお勧めします。そのメソッドは、アプリケーション内の任意のアクティビティから到達可能になります(静的変数または静的メソッドを使用する必要はありません)。

于 2011-07-21T17:44:35.490 に答える
2

プログラムでカスタムフォントを設定する必要がないので、これをチェックしてください。

https://stackoverflow.com/a/27588966/4331353

于 2020-08-19T23:13:44.980 に答える
1

噴水変更はAndroidの非常に基本的な機能であり、ほとんどすべてのアプリケーションに必要です。したがって、開発時間を短縮するために、アプリケーションで1回だけ変更したいので、このリンク FountChanger.classを参照することをお勧めします。

于 2016-02-17T15:06:28.520 に答える
1

パブリックコールを発信し、このようにメソッドをアタッチしました

public class TextViewFontType {

public Typeface typeface;

public void fontTextView(final TextView textView, final String fonttype) {
    typeface = Typeface.createFromAsset(textView.getContext().getAssets(), fonttype);
    textView.setTypeface(typeface);
}

TextViewsetfont-familyメソッドを使用しましたか。

public class FontList {

    public static final String gothicbNormal="fonts/gothicb.ttf";
    public static final String gothicbBold="fonts/gothicb.ttf";
}

2つのパラメーターを渡してメソッドを呼び出すだけでFontListが計算されます。

于 2016-09-01T04:59:06.453 に答える
1

私はdroidkidの答えを受け取り、フォントのファイル名をXMLに直接入力するだけで、どのフォントでも機能するようにしました。

layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto" >

    <!-- where font file is at "assets/fonts/arial.ttf" -->
    <com.odbol.widgets.TextViewWithFont
        ...
        custom:fontFilePath="fonts/arial.ttf" />

</RelativeLayout>

Fonts.java

public class Fonts {

    // use Weak so fonts are freed from memory when you stop using them
    private final static Map<String, Typeface> fonts = new WeakHashMap<>(5);

    /***
     * Returns a font at the given path within the assets directory.
     *
     * Caches fonts to save resources.
     *
     * @param context
     * @param fontPath Path to a font file relative to the assets directory, e.g. "fonts/Arial.ttf"
     * @return
     */
    public synchronized static Typeface getFont(Context context, String fontPath) {
        Typeface font = fonts.get(fontPath);

        if (font == null) {
            font = Typeface.createFromAsset(context.getAssets(), fontPath);
            fonts.put(fontPath, font);
        }

        return font;
    }
}

values / attrs.xml

<resources>

    <declare-styleable name="TextViewWithFont">
        <!-- a path to a font, relative to the assets directory -->
        <attr name="fontFilePath" format="string" />

        <attr name="type">
            <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
        </attr>
    </declare-styleable>
</resources>

TextViewWithFont.java

public class TextViewWithFont extends TextView {
    private int defaultDimension = 0;
    private int TYPE_BOLD = 1;
    private int TYPE_ITALIC = 2;
    private int fontType;
    private int fontName;

    public TextViewWithFont(Context context) {
        super(context);
        init(null, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }
    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.TextViewWithFont, defStyle, 0);
        String fontPath = a.getString(R.styleable.TextViewWithFont_fontFilePath);
        fontType = a.getInt(R.styleable.TextViewWithFont_type, defaultDimension);
        a.recycle();

        if (fontPath != null) {
            setFontType(Fonts.getFont(getContext(), fontPath));
        }
    }
    private void setFontType(Typeface font) {
        if (fontType == TYPE_BOLD) {
            setTypeface(font, Typeface.BOLD);
        } else if (fontType == TYPE_ITALIC) {
            setTypeface(font, Typeface.ITALIC);
        } else {
            setTypeface(font);
        }
    }
}
于 2016-09-21T07:14:55.230 に答える
0

あなたに完全に使用することを願っています:-

TextView text = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
text.setTypeface(font);
于 2013-02-11T09:53:47.590 に答える
0

このライブラリを使用できます:https ://github.com/InflationX/Calligraphy

レイアウトで使用するフォントを追加するだけです。このような:

<TextView
 fontPath="fonts/verdana.ttf"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
于 2016-05-05T10:03:12.577 に答える
0

アセットフォルダの代わりに、.ttfファイルをフォントフォルダに置くことができます。Android 4.1(APIレベル16)以降を実行しているデバイスのXML機能でフォントサポートを使用するには、サポートライブラリ26以降を使用してください。resフォルダーを右クリックし、[新規]->[Androidリソースディレクトリ]->[フォントの選択]->[OK]をクリックします。「myfont.ttf」ファイルを新しく作成したフォントフォルダに置きます。

res / values / styles.xmlに追加、

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/myfont</item>
</style>

レイアウトファイルにandroid:textAppearance = "@ style / customfontstyle"を追加し、

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/customfontstyle"/>

参照:https ://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml

于 2018-08-14T06:24:59.913 に答える
0

//コードでフォントファイルにアクセスし、

Typeface type = Typeface.createFromAsset(getResources().getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);//assign typeface to textview

//アセットフォルダ内->fonts(foldername)-> arial.ttf(font file name)

于 2018-12-17T09:28:49.350 に答える
-1

1.最初にアセットフォルダを追加します>アプリにフォントstyles.ttfsを追加し、 2。
次のような文字列でフォントのアクセスコードを記述します。

<string name="fontregular">OpenSans-Light.ttf</string>
<string name="fontmedium">OpenSans-Regular.ttf</string>

3.以下のようなレイアウトxmlファイルのtextviewコードにアクセスします。

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="@string/fontregular"
    android:textColor="@color/normalfont"
    android:textSize="@dimen/textregular"/>

4.フォントサイズの寸法を追加します:

<dimen name="textregular">14sp</dimen>
<dimen name="textheader">16sp</dimen>
<dimen name="smalltext">12sp</dimen>
<dimen name="littletext">10sp</dimen>
<dimen name="hightfont">18sp</dimen>

5.フォントの色を色で追加します:

<color name="normalfont">#666</color>
<color name="headerfont">#333</color>
<color name="aquablue">#4da8e3</color>
<color name="orange">#e96125</color>

6.次に変更を適用します。穴アプリを変更するのは簡単なプロセスです。幸せなコーディングは笑顔を保ちます。

于 2016-11-05T06:32:32.167 に答える
-3

アセットフォルダからxmlファイルにフォントファイルにアクセスできます。

android:fontFamily = "fonts / roboto_regular.ttf"

fontsは、assetsフォルダーのサブフォルダーです。

于 2015-02-09T07:21:13.483 に答える