如何在Android中更改TextView的fontFamily

Tar*_*rik 711 android textview android-layout typeface

所以我想android:fontFamily在Android中更改,但我没有在Android中看到任何预定义的字体.如何选择其中一个预定义的?我真的不需要定义自己的TypeFace,但我所需要的只是它现在所显示的内容.

<TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />
Run Code Online (Sandbox Code Playgroud)

看来我在那里做的不会真的有效!BTW android:fontFamily="Arial"是一次愚蠢的尝试!

Jak*_*son 1626

从android 4.1/4.2/5.0开始,可以使用以下Roboto字体系列:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black"     // roboto black
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

与...结合

android:textStyle="normal|bold|italic"
Run Code Online (Sandbox Code Playgroud)

这16种变体是可能的:

  • Roboto经常
  • Roboto斜体
  • Roboto大胆
  • Roboto粗体斜体
  • 的Roboto光强
  • Roboto-Light斜体
  • 的Roboto薄
  • Roboto-Thin italic
  • 的Roboto冷凝
  • Roboto-Condensed斜体
  • Roboto-Condensed大胆
  • Roboto-Condensed粗体斜体
  • 的Roboto黑
  • Roboto-Black斜体
  • 的Roboto介质
  • Roboto-Medium斜体

fonts.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

  • 别忘了这个:android:fontFamily ="sans-serif-thin"// roboto thin (16认同)
  • 这是一个很好的清单.有没有人有这个信息来自哪里的链接?如果谷歌在他们的文档中有一个很容易找到的地方,比如TextView上的`android:fontFamily`文档就好了. (9认同)
  • 最新的字体列表可以在[system_fonts.xml](https://android.googlesource.com/platform/frameworks/base/+/master/data/fonts/system_fonts.xml)中找到,如[here]所述(http ://stackoverflow.com/a/24072492/598094) (8认同)
  • Sam Lu是对的,在Android 4.2中添加了"sans-serif-thin" (6认同)
  • 我在[roboto标本书](http://commondatastorage.googleapis.com/androiddevelopers/design/Roboto_Specimen_Book_20111129.pdf)中看到了一个名为"黑色小帽子"的变体,但我没有设法使用它.使用`android:fontFamily ="sans-serif-black-small-caps"`不起作用.有人知道吗? (6认同)
  • 我无法找到任何这些字体系列你在这里输入的内容.我无法一起找到"sans-serif". (3认同)
  • 这将是很好的信息,哦,我不知道,**`TextView` API Javadocs 怎么样**。只是在说'。显然[这是唯一的官方参考](http://developer.android.com/about/versions/android-4.1.html)。 (3认同)
  • 有关此答案信息来源的任何线索?我想进一步阅读它 (2认同)
  • @Ricardo最好的方法是查看源代码:https://android.googlesource.com/platform/frameworks/base/+/lollipop-release/data/fonts/system_fonts.xml和https://android.googlesource.com /platform/frameworks/base/+/master/data/fonts/fonts.xml,这意味着您要使用"sans-serif-condensed-light" (2认同)

Ste*_*ike 197

这是以编程方式设置字体的方法:

TextView tv = (TextView) findViewById(R.id.appname);
Typeface face = Typeface.createFromAsset(getAssets(),
            "fonts/epimodem.ttf");
tv.setTypeface(face);
Run Code Online (Sandbox Code Playgroud)

将字体文件放在您的资源文件夹中.在我的例子中,我创建了一个名为fonts的子目录.

编辑:如果你想知道你的资产文件夹在哪里看到这个问题

  • 虽然这确实有效,但请注意[这可能会造成内存泄漏](https://code.google.com/p/android/issues/detail?id=9904).可以使用[此答案](/sf/answers/1183177271/)进行修复. (33认同)
  • @ScootrNova gothic.ttf或gothic.TTF ??? 照顾案件敏感...... (2认同)

Man*_*ddy 151

Android-Studio 3.0开始, 它非常容易更改字体系列

使用支持库26,它将适用于运行Android API 16及更高版本的设备

fontres目录下创建一个文件font夹.下载您想要的字体并将其粘贴到文件夹中.结构应该是下面的东西

这里

注意:从Android Support Library 26.0开始,您必须声明两组属性(android:和app :),以确保在运行Api 26或更低版本的设备上加载字体.

现在,您可以更改字体的布局使用

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/dancing_script"
app:fontFamily="@font/dancing_script"/>
Run Code Online (Sandbox Code Playgroud)

编程方式更改

 Typeface typeface = getResources().getFont(R.font.myfont);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
 textView.setTypeface(typeface);  
Run Code Online (Sandbox Code Playgroud)

要使用styles.xml更改字体,请创建样式

 <style name="Regular">
        <item name="android:fontFamily">@font/dancing_script</item>
        <item name="fontFamily">@font/dancing_script</item>
        <item name="android:textStyle">normal</item>
 </style>
Run Code Online (Sandbox Code Playgroud)

并将此样式应用于 TextView

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/Regular"/>
Run Code Online (Sandbox Code Playgroud)

您也可以创建自己的字体系列

-右键单击字体文件夹,然后转到" 新建">"字体资源文件".将出现"新建资源文件"窗口.

-输入文件名,然后单击" 确定".新的字体资源XML在编辑器中打开.

例如,在这里编写自己的字体系列

<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>
Run Code Online (Sandbox Code Playgroud)

这只是将特定fontStyle和fontWeight映射到将用于呈现该特定变体的字体资源.fontStyle的有效值是normal或italic; 和fontWeight符合CSS字体重量规范

1.更改布局中的 fontfamily,您可以编写

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/lobster"/>
Run Code Online (Sandbox Code Playgroud)

2.编程方式更改

 Typeface typeface = getResources().getFont(R.font.lobster);
   //or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.lobster);
 textView.setTypeface(typeface);  
Run Code Online (Sandbox Code Playgroud)

改变整个应用程序的字体添加在AppTheme这两行

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="android:fontFamily">@font/your_font</item>
     <item name="fontFamily">@font/your_font</item>
  </style>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档,Android自定义字体教程

  • 注意:目前仅适用于Android Studio 3.0预览版.它在Android Studio 2.3.3上对我不起作用.希望能节省一些时间! (7认同)
  • 你怎么能从片段中得到字体,因为你不能只做`getResources()`?**编辑**:你回答的最后一行对我有用:`字体字体= ResourcesCompat.getFont(context,R.font.myfont);` (2认同)

Jar*_*ler 97

我不得不/system/etc/fonts.xml在最近的一个项目中解析.以下是Lollipop的当前字体系列:

?????????????????????????????????????????????????????????????????
?    ? FONT FAMILY                ? TTF FILE                    ?
?????????????????????????????????????????????????????????????????
?  1 ? casual                     ? ComingSoon.ttf              ?
?  2 ? cursive                    ? DancingScript-Regular.ttf   ?
?  3 ? monospace                  ? DroidSansMono.ttf           ?
?  4 ? sans-serif                 ? Roboto-Regular.ttf          ?
?  5 ? sans-serif-black           ? Roboto-Black.ttf            ?
?  6 ? sans-serif-condensed       ? RobotoCondensed-Regular.ttf ?
?  7 ? sans-serif-condensed-light ? RobotoCondensed-Light.ttf   ?
?  8 ? sans-serif-light           ? Roboto-Light.ttf            ?
?  9 ? sans-serif-medium          ? Roboto-Medium.ttf           ?
? 10 ? sans-serif-smallcaps       ? CarroisGothicSC-Regular.ttf ?
? 11 ? sans-serif-thin            ? Roboto-Thin.ttf             ?
? 12 ? serif                      ? NotoSerif-Regular.ttf       ?
? 13 ? serif-monospace            ? CutiveMono.ttf              ?
?????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

这是解析器(基于FontListParser):

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

/**
 * Helper class to get the current font families on an Android device.</p>
 * 
 * Usage:</p> {@code List<SystemFont> fonts = FontListParser.safelyGetSystemFonts();}</p>
 */
public final class FontListParser {

    private static final File FONTS_XML = new File("/system/etc/fonts.xml");

    private static final File SYSTEM_FONTS_XML = new File("/system/etc/system_fonts.xml");

    public static List<SystemFont> getSystemFonts() throws Exception {
        String fontsXml;
        if (FONTS_XML.exists()) {
            fontsXml = FONTS_XML.getAbsolutePath();
        } else if (SYSTEM_FONTS_XML.exists()) {
            fontsXml = SYSTEM_FONTS_XML.getAbsolutePath();
        } else {
            throw new RuntimeException("fonts.xml does not exist on this system");
        }
        Config parser = parse(new FileInputStream(fontsXml));
        List<SystemFont> fonts = new ArrayList<>();

        for (Family family : parser.families) {
            if (family.name != null) {
                Font font = null;
                for (Font f : family.fonts) {
                    font = f;
                    if (f.weight == 400) {
                        break;
                    }
                }
                SystemFont systemFont = new SystemFont(family.name, font.fontName);
                if (fonts.contains(systemFont)) {
                    continue;
                }
                fonts.add(new SystemFont(family.name, font.fontName));
            }
        }

        for (Alias alias : parser.aliases) {
            if (alias.name == null || alias.toName == null || alias.weight == 0) {
                continue;
            }
            for (Family family : parser.families) {
                if (family.name == null || !family.name.equals(alias.toName)) {
                    continue;
                }
                for (Font font : family.fonts) {
                    if (font.weight == alias.weight) {
                        fonts.add(new SystemFont(alias.name, font.fontName));
                        break;
                    }
                }
            }
        }

        if (fonts.isEmpty()) {
            throw new Exception("No system fonts found.");
        }

        Collections.sort(fonts, new Comparator<SystemFont>() {

            @Override
            public int compare(SystemFont font1, SystemFont font2) {
                return font1.name.compareToIgnoreCase(font2.name);
            }

        });

        return fonts;
    }

    public static List<SystemFont> safelyGetSystemFonts() {
        try {
            return getSystemFonts();
        } catch (Exception e) {
            String[][] defaultSystemFonts = {
                    {
                            "cursive", "DancingScript-Regular.ttf"
                    }, {
                            "monospace", "DroidSansMono.ttf"
                    }, {
                            "sans-serif", "Roboto-Regular.ttf"
                    }, {
                            "sans-serif-light", "Roboto-Light.ttf"
                    }, {
                            "sans-serif-medium", "Roboto-Medium.ttf"
                    }, {
                            "sans-serif-black", "Roboto-Black.ttf"
                    }, {
                            "sans-serif-condensed", "RobotoCondensed-Regular.ttf"
                    }, {
                            "sans-serif-thin", "Roboto-Thin.ttf"
                    }, {
                            "serif", "NotoSerif-Regular.ttf"
                    }
            };
            List<SystemFont> fonts = new ArrayList<>();
            for (String[] names : defaultSystemFonts) {
                File file = new File("/system/fonts", names[1]);
                if (file.exists()) {
                    fonts.add(new SystemFont(names[0], file.getAbsolutePath()));
                }
            }
            return fonts;
        }
    }

    /* Parse fallback list (no names) */
    public static Config parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(in, null);
            parser.nextTag();
            return readFamilies(parser);
        } finally {
            in.close();
        }
    }

    private static Alias readAlias(XmlPullParser parser) throws XmlPullParserException, IOException {
        Alias alias = new Alias();
        alias.name = parser.getAttributeValue(null, "name");
        alias.toName = parser.getAttributeValue(null, "to");
        String weightStr = parser.getAttributeValue(null, "weight");
        if (weightStr == null) {
            alias.weight = 0;
        } else {
            alias.weight = Integer.parseInt(weightStr);
        }
        skip(parser); // alias tag is empty, ignore any contents and consume end tag
        return alias;
    }

    private static Config readFamilies(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        Config config = new Config();
        parser.require(XmlPullParser.START_TAG, null, "familyset");
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            if (parser.getName().equals("family")) {
                config.families.add(readFamily(parser));
            } else if (parser.getName().equals("alias")) {
                config.aliases.add(readAlias(parser));
            } else {
                skip(parser);
            }
        }
        return config;
    }

    private static Family readFamily(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        String name = parser.getAttributeValue(null, "name");
        String lang = parser.getAttributeValue(null, "lang");
        String variant = parser.getAttributeValue(null, "variant");
        List<Font> fonts = new ArrayList<Font>();
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String tag = parser.getName();
            if (tag.equals("font")) {
                String weightStr = parser.getAttributeValue(null, "weight");
                int weight = weightStr == null ? 400 : Integer.parseInt(weightStr);
                boolean isItalic = "italic".equals(parser.getAttributeValue(null, "style"));
                String filename = parser.nextText();
                String fullFilename = "/system/fonts/" + filename;
                fonts.add(new Font(fullFilename, weight, isItalic));
            } else {
                skip(parser);
            }
        }
        return new Family(name, fonts, lang, variant);
    }

    private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        int depth = 1;
        while (depth > 0) {
            switch (parser.next()) {
            case XmlPullParser.START_TAG:
                depth++;
                break;
            case XmlPullParser.END_TAG:
                depth--;
                break;
            }
        }
    }

    private FontListParser() {

    }

    public static class Alias {

        public String name;

        public String toName;

        public int weight;
    }

    public static class Config {

        public List<Alias> aliases;

        public List<Family> families;

        Config() {
            families = new ArrayList<Family>();
            aliases = new ArrayList<Alias>();
        }

    }

    public static class Family {

        public List<Font> fonts;

        public String lang;

        public String name;

        public String variant;

        public Family(String name, List<Font> fonts, String lang, String variant) {
            this.name = name;
            this.fonts = fonts;
            this.lang = lang;
            this.variant = variant;
        }

    }

    public static class Font {

        public String fontName;

        public boolean isItalic;

        public int weight;

        Font(String fontName, int weight, boolean isItalic) {
            this.fontName = fontName;
            this.weight = weight;
            this.isItalic = isItalic;
        }

    }

    public static class SystemFont {

        public String name;

        public String path;

        public SystemFont(String name, String path) {
            this.name = name;
            this.path = path;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在项目中使用上述类.例如,您可以为用户提供一系列字体系列,并根据其偏好设置字体.

一个不完整的小例子:

final List<FontListParser.SystemFont> fonts = FontListParser.safelyGetSystemFonts();
String[] items = new String[fonts.size()];
for (int i = 0; i < fonts.size(); i++) {
    items[i] = fonts.get(i).name;
}

new AlertDialog.Builder(this).setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        FontListParser.SystemFont selectedFont = fonts.get(which);
        // TODO: do something with the font
        Toast.makeText(getApplicationContext(), selectedFont.path, Toast.LENGTH_LONG).show();
    }
}).show();
Run Code Online (Sandbox Code Playgroud)


Rag*_*ood 48

Android不允许您从XML布局设置自定义字体.相反,您必须将特定字体文件捆绑在应用程序的资源文件夹中,并以编程方式进行设置.就像是:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);
Run Code Online (Sandbox Code Playgroud)

请注意,只能在调用setContentView()后运行此代码.此外,Android仅支持某些字体,并且应采用a .ttf (TrueType).otf (OpenType)格式.即便如此,某些字体可能无效.

是一种绝对适用于Android的字体,您可以使用它来确认您的代码是否有效,以防Android不支持您的字体文件.

Android O更新:根据Roger的评论,现在可以使用Android O中的XML.


Ode*_*ner 27

以编程方式设置Roboto:

paint.setTypeface(Typeface.create("sans-serif-thin", Typeface.NORMAL));
Run Code Online (Sandbox Code Playgroud)


bie*_*eux 25

它是一样的android:typeface.

内置字体是:

  • 正常
  • SANS
  • 衬线
  • 等宽

android:typeface.

  • 我认为这不是一回事,但似乎我们不能同时使用它们.现在似乎有不少于三个不同的属性映射到``setTypeface()``.即``fontFamily``,``fontface``和``textStyle``.但我不能为我的生活弄清楚这些是如何精确组合以解决具体的Typeface实例.有没有人想到这个?Google的文档不太有用...... (4认同)

Joa*_*huk 22

如果你以编程方式想要它,你可以使用

label.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);
Run Code Online (Sandbox Code Playgroud)

在哪里SANS_SERIF可以使用:

  • DEFAULT
  • DEFAULT_BOLD
  • MONOSPACE
  • SANS_SERIF
  • SERIF

ITALIC你可以在哪里使用:

  • BOLD
  • BOLD_ITALIC
  • ITALIC
  • NORMAL

所有这些都在Android开发者身上说明


Pra*_*iya 19

Kotlin 代码 - Textview 从资源文件夹设置自定义字体

res -> font -> avenir_next_regular.ttf设置自定义字体

textView!!.typeface = ResourcesCompat.getFont(context!!, R.font.avenir_next_regular)
Run Code Online (Sandbox Code Playgroud)


gau*_*ott 15

我正在使用Chris Jenx设计的优秀图书馆书法,允许您在Android应用程序中使用自定义字体.试试看!


小智 15

我想我为时已晚,但也许这个解决方案对其他人有帮助。要使用自定义字体,请将字体文件放在字体目录中。

textView.setTypeface(ResourcesCompat.getFont(this, R.font.lato));
Run Code Online (Sandbox Code Playgroud)


Moh*_*eem 12

你想要的是不可能的.您必须TypeFace在代码中设置.

XML你可以做什么

android:typeface="sans" | "serif" | "monospace"
Run Code Online (Sandbox Code Playgroud)

除此之外,您无法使用XML中的字体.:)

对于Arial需要设置型的脸在你的代码.


Aka*_*ava 12

一种简单的方法是在项目中添加所需的字体

转到File->New->New Resource Directory 选择字体

这将在您的资源中创建一个新目录font

下载您的字体 (.ttf)。我使用https://fonts.google.com同样

将其添加到您的字体文件夹,然后在 XML 中或以编程方式使用它们。

XML -

<TextView 
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/your_font"/>
Run Code Online (Sandbox Code Playgroud)

以编程方式 -

 Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
 textView.setTypeface(typeface); 
Run Code Online (Sandbox Code Playgroud)

  • 更好地使用“ResourcesCompat.getFont”方法 (15认同)

and*_*per 11

管理字体的简单方法是通过资源声明它们,如下:

<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>

<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>

<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>
Run Code Online (Sandbox Code Playgroud)

这是基于此处此处的源代码


ana*_*ish 9

动态地你可以使用这个在xml中设置类似于android:fontFamily的fontfamily,

For Custom font:

 TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
 Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"); 
 tv.setTypeface(face);

For Default font:

 tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));
Run Code Online (Sandbox Code Playgroud)

这些是使用的默认字体系列的列表,通过替换双引号字符串"sans-serif-medium"来使用任何一个

FONT FAMILY                    TTF FILE                    

1  casual                      ComingSoon.ttf              
2  cursive                     DancingScript-Regular.ttf   
3  monospace                   DroidSansMono.ttf           
4  sans-serif                  Roboto-Regular.ttf          
5  sans-serif-black            Roboto-Black.ttf            
6  sans-serif-condensed        RobotoCondensed-Regular.ttf 
7  sans-serif-condensed-light  RobotoCondensed-Light.ttf   
8  sans-serif-light            Roboto-Light.ttf            
9  sans-serif-medium           Roboto-Medium.ttf           
10  sans-serif-smallcaps       CarroisGothicSC-Regular.ttf 
11  sans-serif-thin            Roboto-Thin.ttf             
12  serif                      NotoSerif-Regular.ttf       
13  serif-monospace            CutiveMono.ttf              
Run Code Online (Sandbox Code Playgroud)

"mycustomfont.ttf"是ttf文件.路径将在src/assets/fonts/mycustomfont.ttf中,您可以在此默认字体系列中详细介绍默认字体


小智 6

通过一些反复试验,我学到了以下内容.

在*.xml中,您可以将stock字体与以下函数组合在一起,而不仅仅是字体:

 android:fontFamily="serif" 
 android:textStyle="italic"
Run Code Online (Sandbox Code Playgroud)

使用这两种样式,在任何其他情况下都不需要使用字体.使用fontfamily和textStyle,组合范围要大得多.


小智 6

尝试这个:

TextView textview = (TextView) findViewById(R.id.textview);
Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);
Run Code Online (Sandbox Code Playgroud)


Mak*_*vin 6

Typeface typeface = ResourcesCompat.getFont(context, R.font.font_name);
textView.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)

通过编程轻松地从res> font目录将字体设置为任何textview


小智 6

如果您使用的是 Android Studio 3.5+,更改字体非常简单。在设计视图中选择文本小部件并在属性窗口中检查 fontFamily。值下拉列表包含您可以从中选择一种的所有可用字体。如果您正在寻找 Google 字体,请单击更多字体选项。

属性窗口 属性窗口

谷歌字体 谷歌字体


Ter*_*Liu 5

android:fontFamily的有效值是在/system/etc/system_fonts.xml(4.x)或/system/etc/fonts.xml(5.x)中定义的。但是设备制造商可能会对其进行修改,因此通过设置fontFamily值使用的实际字体取决于指定设备的上述文件。

在AOSP中,Arial字体有效,但必须使用“ arial”而不是“ Arial”进行定义,例如android:fontFamily =“ arial”。快速了解Kitkat的system_fonts.xml

    <family>
    <nameset>
        <name>sans-serif</name>
        <name>arial</name>
        <name>helvetica</name>
        <name>tahoma</name>
        <name>verdana</name>
    </nameset>
    <fileset>
        <file>Roboto-Regular.ttf</file>
        <file>Roboto-Bold.ttf</file>
        <file>Roboto-Italic.ttf</file>
        <file>Roboto-BoldItalic.ttf</file>
    </fileset>
</family>
Run Code Online (Sandbox Code Playgroud)

///////////////////////////////////////////////////// ////////////////////////

定义布局中的“字体”存在三个相关的xml属性-android :fontFamilyandroid:typefaceandroid:textStyle。“ fontFamily”和“ textStyle”或“ typeface”和“ textStyle”的组合可用于更改文本中字体的外观,因此也可以单独使用。TextView.java中的代码片段如下所示:

    private void setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) {
    Typeface tf = null;
    if (familyName != null) {
        tf = Typeface.create(familyName, styleIndex);
        if (tf != null) {
            setTypeface(tf);
            return;
        }
    }
    switch (typefaceIndex) {
        case SANS:
            tf = Typeface.SANS_SERIF;
            break;

        case SERIF:
            tf = Typeface.SERIF;
            break;

        case MONOSPACE:
            tf = Typeface.MONOSPACE;
            break;
    }
    setTypeface(tf, styleIndex);
}


    public void setTypeface(Typeface tf, int style) {
    if (style > 0) {
        if (tf == null) {
            tf = Typeface.defaultFromStyle(style);
        } else {
            tf = Typeface.create(tf, style);
        }

        setTypeface(tf);
        // now compute what (if any) algorithmic styling is needed
        int typefaceStyle = tf != null ? tf.getStyle() : 0;
        int need = style & ~typefaceStyle;
        mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
        mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
    } else {
        mTextPaint.setFakeBoldText(false);
        mTextPaint.setTextSkewX(0);
        setTypeface(tf);
    }
}
Run Code Online (Sandbox Code Playgroud)

从代码中我们可以看到:

  1. 如果设置了“ fontFamily”,则“字体”将被忽略。
  2. “字体”具有标准和有限的有效值。实际上,这些值是“普通”,“无”,“ serif”和“等宽”,可以在system_fonts.xml(4.x)或fonts.xml(5.x)中找到。实际上,“ normal”和“ sans”都是系统的默认字体。
  3. “ fontFamily”可用于设置内置字体的所有字体,而“ typeface”仅提供“ sans-serif”,“ serif”和“ monospace”(世界上字体类型的三个主要类别)的典型字体。 。
  4. 当仅设置“ textStyle”时,我们实际上设置了默认字体和指定的样式。有效值为“正常”,“粗体”,“斜体”和“粗体|斜体”。


Wol*_*bae 5

您也可以通过在 res 目录下添加一个字体文件夹来做到这一点,如下所示。

在此处输入图片说明

然后,选择字体作为资源类型。 在此处输入图片说明

你可以从https://www.1001fonts.com/找到可用的字体,然后将 TTF 文件解压到这个字体目录。

在此处输入图片说明

最后,只需通过添加 android:fontFamily:"@font/urfontfilename" 来更改包含文本视图的 XML 文件

在此处输入图片说明


小智 5

要通过程序设置字体,请编写...

 TextView tv7 = new TextView(this);
 tv7.setText(" TIME ");    
 tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
 tv7.setTextSize(12);
 tbrow.addView(tv7);
Run Code Online (Sandbox Code Playgroud)

名称“sans-serif-condensed”是从 fonts.xml 文件引用的,该文件应在应用程序--> res--> 值文件夹中创建,并在其中保存字体。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

希望这是清楚的!


归档时间:

查看次数:

761238 次

最近记录:

6 年 前