268

にカスタム フォントを適用しましたTextViewが、書体が変更されないようです。

これが私のコードです:

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);

誰か私をこの問題から解放してくれませんか?

4

21 に答える 21

231

Mobiletuts +には、Androidのテキストフォーマットに関する非常に優れたチュートリアルがあります。クイックヒント:Androidフォントをカスタマイズする

編集:今それを自分でテストしました。これが解決策です。fontsというサブフォルダーを使用できますが、フォルダーではassetsなくフォルダーに配置する必要がありresます。それで

アセット/フォント

また、フォントの終わり、つまりフォントファイル自体の終わりがすべて小文字であることを確認してください。言い換えれば、そうではないはずですmyFont.TTFが、myfont.ttf この方法は小文字でなければなりません

于 2010-09-06T11:45:20.940 に答える
33

すでに良い答えがあることは知っていますが、完全に機能する実装を次に示します。

カスタム テキスト ビューは次のとおりです。

package com.mycompany.myapp.widget;

/**
 * Text view with a custom font.
 * <p/>
 * In the XML, use something like {@code customAttrs:customFont="roboto-thin"}. The list of fonts
 * that are currently supported are defined in the enum {@link CustomFont}. Remember to also add
 * {@code xmlns:customAttrs="http://schemas.android.com/apk/res-auto"} in the header.
 */
public class CustomFontTextView extends TextView {

    private static final String sScheme =
            "http://schemas.android.com/apk/res-auto";
    private static final String sAttribute = "customFont";

    static enum CustomFont {
        ROBOTO_THIN("fonts/Roboto-Thin.ttf"),
        ROBOTO_LIGHT("fonts/Roboto-Light.ttf");

        private final String fileName;

        CustomFont(String fileName) {
            this.fileName = fileName;
        }

        static CustomFont fromString(String fontName) {
            return CustomFont.valueOf(fontName.toUpperCase(Locale.US));
        }

        public Typeface asTypeface(Context context) {
            return Typeface.createFromAsset(context.getAssets(), fileName);
        }
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (isInEditMode()) {
            return;
        } else {
            final String fontName = attrs.getAttributeValue(sScheme, sAttribute);

            if (fontName == null) {
                throw new IllegalArgumentException("You must provide \"" + sAttribute + "\" for your text view");
            } else {
                final Typeface customTypeface = CustomFont.fromString(fontName).asTypeface(context);
                setTypeface(customTypeface);
            }
        }
    }
}

カスタム属性は次のとおりです。res/attrs.xmlこれはあなたのファイルに行くはずです:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomFontTextView">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>

で、使い方はこんな感じ。相対レイアウトを使用してそれをラップし、customAttr宣言を表示しますが、既存のレイアウトをそのまま使用することもできます。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:customAttrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.mycompany.myapp.widget.CustomFontTextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="foobar"
         customAttrs:customFont="roboto_thin" />

</RelativeLayout>
于 2014-09-28T20:29:43.483 に答える
14

私はこれを以前にうまく使用しました。実装の唯一の違いは、アセットでサブフォルダーを使用していなかったことです。ただし、それで何かが変わるかどうかはわかりません。

于 2010-09-06T11:35:25.150 に答える
7

https://github.com/neopixl/PixlUIで PixlUI を使用できます。

.jar をインポートして XML で使用する

 <com.neopixl.pixlui.components.textview.TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    pixlui:typeface="GearedSlab.ttf" />
于 2013-08-07T06:47:03.487 に答える
4

SOで提示されたすべてのソリューションに満足できなかったので、私は自分のものを思いつきました。これは、タグを使ったちょっとしたトリック (つまり、コード内でタグを使用できない) に基づいており、そこにフォント パスを配置しました。したがって、ビューを定義するときは、次のいずれかを実行できます。

<TextView
        android:id="@+id/textViewHello1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 1"
        android:tag="fonts/Oswald-Regular.ttf"/>

またはこれ:

<TextView
        android:id="@+id/textViewHello2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 2"
        style="@style/OswaldTextAppearance"/>

<style name="OswaldTextAppearance">
        <item name="android:tag">fonts/Oswald-Regular.ttf</item>
        <item name="android:textColor">#000000</item>
</style>

これで、次のようにビューに明示的にアクセス/セットアップできます。

TextView textView = TextViewHelper.setupTextView(this, R.id.textViewHello1).setText("blah");

または、次の方法ですべてをセットアップします。

TextViewHelper.setupTextViews(this, (ViewGroup) findViewById(R.id.parentLayout)); // parentLayout is the root view group (relative layout in my case)

そして、あなたが尋ねる魔法のクラスは何ですか?アクティビティとフラグメントの両方のヘルパー メソッドを使用して、ほとんど別の SO 投稿から接着されています。

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

public class TextViewHelper {
    private static final Map<String, Typeface> mFontCache = new HashMap<>();

    private static Typeface getTypeface(Context context, String fontPath) {
        Typeface typeface;
        if (mFontCache.containsKey(fontPath)) {
            typeface = mFontCache.get(fontPath);
        } else {
            typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
            mFontCache.put(fontPath, typeface);
        }
        return typeface;
    }

    public static void setupTextViews(Context context, ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setupTextViews(context, (ViewGroup) child);
            } else {
                if (child != null) {
                    TextViewHelper.setupTextView(context, child);
                }
            }
        }
    }

    public static void setupTextView(Context context, View view) {
        if (view instanceof TextView) {
            if (view.getTag() != null) // also inherited from TextView's style
            {
                TextView textView = (TextView) view;
                String fontPath = (String) textView.getTag();
                Typeface typeface = getTypeface(context, fontPath);
                if (typeface != null) {
                    textView.setTypeface(typeface);
                }
            }
        }
    }

    public static TextView setupTextView(View rootView, int id) {
        TextView textView = (TextView) rootView.findViewById(id);
        setupTextView(rootView.getContext().getApplicationContext(), textView);
        return textView;
    }

    public static TextView setupTextView(Activity activity, int id) {
        TextView textView = (TextView) activity.findViewById(id);
        setupTextView(activity.getApplicationContext(), textView);
        return textView;
    }
}
于 2016-08-12T03:10:16.633 に答える
1

同じ問題があり、TTF が表示されませんでした。フォントファイルを変更しましたが、同じコードで動作しています。

于 2013-05-18T19:54:37.603 に答える
1

ネットワークからフォントをロードしたり、簡単にスタイルを設定したい場合は、次を使用できます。

https://github.com/shellum/fontView

例:

<!--Layout-->
<com.finalhack.fontview.FontView
        android:id="@+id/someFontIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />

//Java:
fontView.setupFont("http://blah.com/myfont.ttf", true, character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);
于 2013-05-29T21:13:37.297 に答える