我将自定义字体应用于 TextView, ,但似乎并没有更改字体。

这是我的代码:

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

有人可以让我摆脱这个问题吗?

有帮助吗?

解决方案

在Mobiletuts+关于Android的文本格式的教程非常好。 快速提示:自定义Android字体

编辑:我自己进行了测试。这是解决方案。您可以使用名为字体的子文件夹,但必须进入 assets 文件夹而不是 res 文件夹。所以

资产/字体

另外,请确保字体结尾我的意思是字体文件本身的结尾都是较低的情况。换句话说,它不应该是 myFont.TTFmyfont.ttf 这种方式必须在较低的情况下

其他提示

在尝试了此线程中描述的大多数解决方案之后,我不小心发现了书法(https://github.com/chrisjenx/calligraphy) - 克里斯托弗·詹金斯(Christopher Jenkins)的图书馆,可让您轻松地在应用中添加自定义字体。与此处建议的方法相比,他的自由lib的优势是:

  1. 您不必介绍自己的Overriden TextView组件,而是使用内置文本视图
  2. 您可以轻松使用Gradle包含图书馆
  3. 图书馆不会限制您选择字体;您只需将自己喜欢的资产添加到资产
  4. 您不仅可以获得自定义文本视图 - 所有其他基于文本的Android组合也将使用您的自定义字体显示。

我知道已经有一个很好的答案,但是这里有一个完全有效的实现。

这是自定义文本视图:

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>

我以前成功使用过。我们实施之间的唯一区别是我没有在资产中使用子文件夹。不知道这是否会改变任何东西。

只要您将字体放置在正确的位置,并且字体文件本身没有错误,则您的代码应该像rattlesnake一样工作。

但是,如果您只能在布局XML中定义字体,那将容易得多,这样:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!-- This text view is styled with the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This uses my font in bold italic style" />

    <!-- This text view is styled here and overrides the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:flFont="anotherFont"
        android:textStyle="normal"
        android:text="This uses another font in normal style" />

    <!-- This text view is styled with a style and overrides the app theme -->
    <com.innovattic.font.FontTextView
        style="@style/StylishFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This also uses another font in normal style" />

</LinearLayout>

与随附的 res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <!-- Application theme -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:textViewStyle">@style/MyTextViewStyle</item>
    </style>

    <!-- Style to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView">
        <item name="android:textAppearance">@style/MyTextAppearance</item>
    </style>

    <!-- Text appearance to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo">
        <!-- Alternatively, reference this font with the name "aspergit" -->
        <!-- Note that only our own TextView's will use the font attribute -->
        <item name="flFont">someFont</item>
        <item name="android:textStyle">bold|italic</item>
    </style>

    <!-- Alternative style, maybe for some other widget -->
    <style name="StylishFont">
        <item name="flFont">anotherFont</item>
        <item name="android:textStyle">normal</item>
    </style>

</resources>

我专门为此目的创建了几个工具。参考 这个项目 来自github,或看看这个 博客文章 这解释了整个事情。

对于Android中的自定义字体,在资产夹中创建一个文件夹文件夹名称“字体”“字体”将所需的fonts.ttf或.otf文件放入其中。

如果您扩展了uibaseFragment:

Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arial.ttf");
        tv.setTypeface(font);

否则如果扩展活动:

Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Arial.ttf");
        tv.setTypeface(font);

从Android O Preview版本中完成此操作的最佳方法就是这样:

它仅在您拥有Android Studio-2.4或更高时起作用

  1. 右键单击 RES文件夹 然后去 新> Android资源目录. 。新的
    出现资源目录窗口。
  2. 在资源类型列表中,选择 字体, ,然后单击确定。
  3. 在字体文件夹中添加您的字体文件。下面的文件夹结构生成 R.font.dancing_script, R.font.la_la, , 和 R.font.ba_ba.
  4. 双击 一个字体文件,用于预览编辑器中的文件字体。

接下来,我们必须创建一个字体家庭:

  1. 右键单击字体文件夹,然后转到 新>字体资源文件. 。出现新的资源文件窗口。
  2. 输入 文件名,然后单击确定. 。新的字体资源XML在编辑器中打开。
  3. 将每个字体文件,样式和权重属性包装在字体标签元素中。以下XML说明了字体资源XML中添加与字体相关的属性:

将字体添加到文本视图中:

   <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/hey_fontfamily"/>

如文档

使用字体

所有步骤都是正确的。

您可以在 https://github.com/neopixl/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" />

由于我对所有提出的解决方案都不满意,因此我想出了我的想法。它基于带有标签的小技巧(即您不能在代码中使用标签),我将字体路径放在那里。因此,在定义视图时,您可以做到这一点:

<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;
    }
}

不幸的是,对此没有好的解决方案。

我已经看到了许多有关使用自定义文本视图的文章,但是他们忘记的是,不仅可以实现字体,而且在其他视图中隐藏了文本视图,而开发人员无法访问。我什至不会开始 可跨度.

您可以使用外部字体实用程序,例如:

书法字体工具

该循环通过应用程序创建的应用程序中的每个视图循环,甚至该实用程序都错过了一些视图(ViewPager呈现正常字体),那么您遇到的问题是,当Google更新其构建工具时,这有时会崩溃,因为它需要针对弃用的属性。它也有点慢 爪哇的反思.

真正取决于Google来解决此问题。我们需要在Android中更好的字体支持。如果您查看iOS的解决方案,它们实际上将内置100个字体可供选择。想要自定义字体吗?只需放入tff,它是可用的。

目前,现在仅限于Google为我们提供的提供,这非常有限,但幸运的是进行了移动优化。

确保将上述代码粘贴到OnCreate()中 您呼叫超级和呼叫setContentView()。这个小细节使我挂了一段时间。

Android 8.0 在应用程序中使用自定义字体变得很容易 downloadable fonts。我们可以将字体直接添加到 res/font/ folder 在Project文件夹中,这样做的字体将在Android Studio中自动提供。

Folder Under res with name font and type set to Font

现在设置 fontFamily 属性为字体列表,或单击更多内容,然后选择您选择的字体。这会 添加 tools:fontFamily="@font/your_font_file" 在您的文本视图上行。

这将自动生成几个文件。

1. 在值文件夹中,它将创建 fonts_certs.xml.

2. 在清单中,它将添加此行:

  <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" /> 

3. preloaded_fonts.xml

<resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/open_sans_regular</item>
        <item>@font/open_sans_semibold</item>
    </array>
</resources>

我遇到了同样的问题,TTF没有出现。我更改了字体文件,并使用相同的代码工作。

如果要从网络加载字体或轻松样式,则可以使用:

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);

好吧,七年后,您可以更改整个应用程序 textView 或您想要使用的东西 android.support 库26 ++。

例如:

创建您的字体软件包 App/src/res/font 并将您的字体转入其中。

enter image description here

在您的应用主题中,只需将其添加为一个fontfomily:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   . . . ...
    <item name="android:fontFamily">@font/demo</item>
</style>

textView 只要:

<style name="fontTextView" parent="@android:style/Widget.TextView">
    <item name="android:fontFamily">monospace</item>
</style>

并添加到您的主要主题中:

<item name="android:textViewStyle">@style/fontTextView</item>

目前已经处理过 8.1直到4.1 API果冻豆 那是一个广泛的范围。

更新答案:Android 8.0(API级别26)引入了一个新功能,即XML中的字体。只需在运行Android 4.1(API级别16)及更高的设备上使用XML功能中的字体,请使用支持库26。

看到这个 关联


旧答案

有两种自定义字体的方法:

!!!我在资产/字体/iran_sans.ttf中的自定义字体



路1:反射thepeface.class ||| 最好的办法

在类扩展应用程序中,请致电Fontsoverride.setDefaultFont(),此代码将导致所有软件字体更改,甚至是Toasts字体

AppController.java

public class AppController extends Application {

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

        //Initial Font
        FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");

    }
}

fontsoverride.java

public class FontsOverride {

    public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    private 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();
        }
    }
}



路2: 使用setTypeface

对于特殊视图,只需调用settypeface()更改字体即可。

ctextview.java

public class CTextView extends TextView {

    public CTextView(Context context) {
        super(context);
        init(context,null);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    public void init(Context context, @Nullable AttributeSet attrs) {

        if (isInEditMode())
            return;

        // use setTypeface for change font this view
        setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));

    }
}

fontutils.java

public class FontUtils {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<>();

    public static Typeface getTypeface(String fontName) {
        Typeface tf = fontCache.get(fontName);
        if (tf == null) {
            try {
                tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }

}

您可以使用简单而简单 EasyFonts 第三方库将各种自定义字体设置为您 TextView. 。通过使用此库,您不必担心在资产/字体文件夹中下载和添加字体。还与字体对象创建有关。

代替

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

简单地:

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));

该库还提供以下字体面。

  • 机器人
  • 机器人衬线
  • 机器人机器人
  • 自由
  • 有趣的提升者
  • Android国家
  • 绿色鳄梨
  • 认出

从API 26到API 26的正确方法在此处介绍:

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

这涉及将TTF文件放置在RES/FONT文件夹中并创建一个字体家庭文件。

现在支持的最简单的Android解决方案!

在XML中使用自定义字体:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/[your font resource]"/>

查看详细信息:

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

  • 打开您的项目并选择 项目 在左上角
  • 应用程序 --> src --> 主要的
  • 右键单击以Main并创建目录名称为 资产
  • 右键单击以进行评估并创建新目录名称 字体
  • 您需要找到免费字体 免费字体
  • 将其输入您的文本视图并在您的活动课中称为
  • 复制您的字体 字体 文件夹
  • TextView txt = (TextView) findViewById(R.id.txt_act_spalsh_welcome); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Aramis Italic.ttf"); txt.setTypeface(font);

字体的名称必须是正确的,并且玩得开心

是的,可下载字体非常简单,如 dipali s 说过。

这就是你的方式...

  1. 放置 TextView.
  2. 在属性窗格中,选择 fontFamily 落下。如果不存在,请找到Caret的东西(>并单击它以展开 textAppearance) 在下面。
  3. 扩展 font-family 落下。
  4. 在小列表中,一直向下滚动直到看到 more fonts
  5. 这将打开一个对话框,您可以在其中搜索 Google Fonts
  6. 在顶部搜索您喜欢的字体
  7. 选择您的字体。
  8. 选择您喜欢的字体的样式(即粗体,正常,斜体等)
  9. 在右窗格中,选择“广播”按钮说 Add font to project
  10. 点击好的。现在,您的文本视图具有您喜欢的字体!

奖金:如果您想使用所选字体中的应用程序中的文字样式,请添加 <item name="android:fontfamily">@font/fontnamehere</item> 进入你的 styles.xml

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top