Cómo cambiar fontFamily de TextView en Android


Así que me gustaría cambiar el android:fontFamily en Android, pero no veo ninguna fuente predefinida en Android. ¿Cómo selecciono uno de los predefinidos? En realidad no necesito definir mi propio tipo de Letra, pero todo lo que necesito es algo diferente de lo que muestra ahora.

<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"
 />

¡Parece que lo que hice allí no funcionará! BTW android:fontFamily="Arial" fue un intento estúpido!

Author: Piyush, 2012-08-26

25 answers

Desde android 4.1 / 4.2 / 5.0, las siguientes Familias de fuentes Roboto están disponibles:

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)

introduzca la descripción de la imagen aquí

En combinación con

android:textStyle="normal|bold|italic"

Estas 16 variantes son posibles:

  • Roboto regular
  • Roboto italic
  • Roboto bold
  • Roboto negrita cursiva
  • Roboto-Light
  • Roboto-Luz cursiva
  • Roboto-Thin
  • Roboto - Thin italic
  • Roboto-Condensado
  • Roboto-Cursiva condensada
  • Roboto-Negrita condensada
  • Roboto-Negrita condensada cursiva
  • Roboto-Black
  • Roboto-Cursiva negra
  • Roboto-Medium
  • Roboto-Medio cursiva

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>
 1507
Author: Jakob Eriksson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-18 13:58:54

Esta es la forma de establecer la fuente programáticamente:

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

Coloque el archivo de fuente en la carpeta assets. En mi caso he creado un subdirectorio llamado fonts.

EDITAR: {[7] } Si se pregunta dónde está su carpeta de activos, consulte esta pregunta

 159
Author: Stefan Beike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:48

Tuve que analizar /system/etc/fonts.xml en un proyecto reciente. Aquí están las familias de fuentes actuales a partir de 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              ║
╚════╩════════════════════════════╩═════════════════════════════╝

Aquí está el analizador (basado en 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;
        }

    }
}

Siéntase libre de usar la clase anterior en su proyecto. Por ejemplo, puede dar a sus usuarios una selección de familias de fuentes y establecer el tipo de letra en función de sus preferencias.

Un pequeño ejemplo incompleto:

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();
 89
Author: Jared Rummler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-09 10:25:46

A partir de Android-Studio 3.0 es muy fácil cambiar la familia de fuentes

Usando la biblioteca de soporte 26, funcionará en dispositivos que ejecuten la API de Android versión 16 y superior

Crea una carpeta font bajo el directorio res.Descarga la fuente que quieras y pégala dentro de la carpeta font. La estructura debe ser algo como abajo

Aqui

Ahora puede cambiar la fuente en layout usando

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

A change Programatically

 Typeface typeface = getResources().getFont(R.font.myfont);
 textView.setTypeface(typeface);  

Para cambiar la fuente usando estilos .xml crear un estilo

 <style name="Regular">
        <item name="android:fontFamily">@font/dancing_script</item>
        <item name="android:textStyle">normal</item>
 </style>

Y aplicar este estilo a TextView

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/Regular"/>

También puede crear su propia familia de fuentes

- Haga clic con el botón derecho en la carpeta de fuentes y vaya a Nuevo > Archivo de fuentes. Aparecerá la ventana Nuevo Archivo de Recursos.

- Introduzca el nombre del archivo y, a continuación, haga clic en OK. El nuevo recurso de fuentes XML se abre en el editor.

Escriba su propia familia de fuentes aquí, por ejemplo

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

Esto es simplemente una asignación de un estilo de fuente y un peso de fuente específicos al recurso de fuente que se utilizará para representar esa variante específica. Los valores válidos para fontStyle son normales o cursiva; y fontWeight se ajusta a la especificación CSS font-weight

1. To change fontfamily in layout you can write

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

2. A Change Programáticamente

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

Nota: A partir de la Biblioteca de soporte de Android 26.0, debe declarar ambos conjuntos de atributos (android: y app:) para garantizar que sus fuentes se carguen en dispositivos que se ejecuten Api 26 o inferior.

  <?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto">
    <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/myfont-Regular"
          app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont-Regular"/>
    <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/myfont-Italic"
          app:fontStyle="italic" app:fontWeight="400" app:font="@font/myfont-Italic" />
</font-family>

Para cambiar la fuente de toda la aplicación, Agregue estas dos líneas en 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>

Ver la Documentación , Android Custom Fonts Tutorial Para más información

 72
Author: Redman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-04 06:17:33

Android no permite establecer fuentes personalizadas desde el diseño XML. En su lugar, debe agrupar el archivo de fuente específico en la carpeta assets de su aplicación y configurarlo mediante programación. Algo como:

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

Tenga en cuenta que solo puede ejecutar este código después de que se haya llamado a setContentView (). Además, solo algunas fuentes son compatibles con Android, y deben estar en un formato .ttf (TrueType) o .otf (OpenType). Incluso entonces, algunas fuentes pueden no funcionar.

Esta es una fuente que definitivamente funciona en Android, y puedes usa esto para confirmar que tu código funciona en caso de que tu archivo de fuente no sea compatible con Android.

Actualización de Android O: Esto ahora es posible con XML en Android O , basado en el comentario de Roger.

 43
Author: Raghav Sood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-26 13:25:37

Es lo mismo que android:typeface.

Las fuentes incorporadas son:

  • normal
  • sans
  • serif
  • monoespacio

Ver android:tipo de letra.

 24
Author: biegleux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 07:41:59

Para configurar Roboto mediante programación:

paint.setTypeface(Typeface.create("sans-serif-thin", Typeface.NORMAL));
 23
Author: WhereDatApp.com,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-06 22:59:40

Si lo desea programáticamente, podría usar

label.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);

Donde SANS_SERIF puedes usar:

  • DEFAULT
  • DEFAULT_BOLD
  • MONOSPACE
  • SANS_SERIF
  • SERIF

Y donde ITALIC puedes usar:

  • BOLD
  • BOLD_ITALIC
  • ITALIC
  • NORMAL

Todo está indicado en los desarrolladores de Android

 20
Author: Joaquin Iurchuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 19:39:10

Estoy usando excelente biblioteca Caligrafía por Chris Jenx diseñado para permitir el uso de fuentes personalizadas en su aplicación Android. ¡Inténtalo!

 14
Author: gauravdott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-06 13:50:38

Lo que quieres no es posible. Debe establecer TypeFace en su Código.

{[4] {} En[2]} lo que puedes hacer es
android:typeface="sans" | "serif" | "monospace"

Otro entonces esto no se puede jugar mucho con las fuentes en XML. :)

Para Arial necesitas establecer type face en tu código.

 11
Author: Mohsin Naeem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 07:38:37

Una forma fácil de administrar las fuentes sería declararlas a través de recursos, como tal:

<!--++++++++++++++++++++++++++-->
<!--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>

Esto se basa en el código fuente aquí y aquí

 9
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-23 21:52:04

Dinámicamente puede establecer la familia de fuentes similar a android: fontFamily en xml usando esto,

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

Estas son las listas de fuente predeterminada familia utilizada, utilice cualquiera de estos sustituyendo la cadena de comillas dobles "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              

"mycustomfont.ttf" es el archivo ttf. Ruta estará en src/assets/fonts/mycustomfont.ttf , puede consultar más sobre la fuente predeterminada en esta Familia de fuentes predeterminada

 8
Author: anand krish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 13:03:49

Hice una pequeña biblioteca llamada Foundry que puede usar para aplicar tipos de letra personalizados a través de diseños y estilos XML.

 7
Author: Joseph Earl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-20 08:10:18

Con algún ensayo y error aprendí lo siguiente.

Dentro del *.xml puede combinar las fuentes de stock con las siguientes funciones, no solo con el tipo de letra:

 android:fontFamily="serif" 
 android:textStyle="italic"

Con estos dos estilos, no había necesidad de usar tipografía en ningún otro caso. La gama de combinaciones es mucho más grande con fontfamily&textStyle.

 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-08 10:17:21

El valor válido de android:fontFamily se define en /system/etc/system_fonts.xml(4.x) o /system/etc/fonts.xml(5.x). Sin embargo, el fabricante del dispositivo podría modificarlo, por lo que la fuente real utilizada al establecer el valor fontFamily depende del archivo mencionado anteriormente del dispositivo especificado.

En AOSP, la fuente Arial es válida pero debe definirse usando "arial" no "Arial", por ejemplo android:fontFamily="arial". Echa un vistazo a qucik Kitkat's 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>

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

Hay tres atributos xml relevantes para definir una "fuente" en el diseño { android: fontFamily, android: tipo de letra y android:Estilo de texto. La combinación de "fontFamily" y "textStyle" o "typeface" y "textStyle" se puede usar para cambiar la apariencia de la fuente en el texto, también se usa sola. Fragmento de código en TextView.java me gusta esto:

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

Del código podemos ver:

  1. si se establece "fontFamily", entonces el "tipo de letra" será ignorado.
  2. "tipo de letra" tiene valores válidos estándar y limitados. De hecho, los valores son "normal ""sans" "serif" y "monospace", se pueden encontrar en system_fonts.xml(4.x) o fuentes.xml(5.x). En realidad, tanto "normal" como "sans" son la fuente predeterminada del sistema.
  3. "fontFamily" se puede usar para establecer todas las fuentes de fuentes integradas, mientras que "typeface" solo proporciona tipografías típicas de "sans-serif ""serif" y "monospace" (las tres categorías principales de tipo de fuente en el mundo).
  4. Cuando solo se establece "textStyle", en realidad se establece la fuente predeterminada y el estilo especificado. El valor efectivo es "normal" "negrita" "cursiva"y" negrita | cursiva".
 4
Author: Terry Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-04 08:35:26
<string name="font_family_display_4_material">sans-serif-light</string>
<string name="font_family_display_3_material">sans-serif</string>
<string name="font_family_display_2_material">sans-serif</string>
<string name="font_family_display_1_material">sans-serif</string>
<string name="font_family_headline_material">sans-serif</string>
<string name="font_family_title_material">sans-serif-medium</string>
<string name="font_family_subhead_material">sans-serif</string>
<string name="font_family_menu_material">sans-serif</string>
<string name="font_family_body_2_material">sans-serif-medium</string>
<string name="font_family_body_1_material">sans-serif</string>
<string name="font_family_caption_material">sans-serif</string>
<string name="font_family_button_material">sans-serif-medium</string>
 2
Author: Yang Peiyong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-19 07:33:44

Esta es también una buena biblioteca RobotoTextView. Realmente sirve a sus necesidades.

 1
Author: Aleksei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-13 10:56:10

Pones estilo en res/layout/value/style.xml así:

<style name="boldText">
    <item name="android:textStyle">bold|italic</item>
    <item name="android:textColor">#FFFFFF</item>
</style>

Y para usar este estilo en el archivo main.xml use:

style="@style/boldText"
 1
Author: rajender,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-01 13:44:43

Aquí hay un más fácil wa y que puede funcionar en algunos casos. El principio es agregar un TextVview no visible en su diseño xml y obtener su tipo de letra en el código java.

El diseño en el archivo xml:

 <TextView
        android:text="The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty."
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif-thin"
        android:id="@+id/textViewDescription"/>

Y el código java:

myText.setTypeface(textViewSelectedDescription.getTypeface());

Ha funcionado para mí (dentro de un TextSwitcher, por ejemplo).

 1
Author: Frédéric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 09:47:41

Si desea usar un TextView en tantos lugares con la misma familia de fuentes, extienda la clase TextView y establezca su fuente de la siguiente manera: -

public class ProximaNovaTextView extends TextView {

    public ProximaNovaTextView(Context context) {
        super(context);

        applyCustomFont(context);
    }

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

        applyCustomFont(context);
    }

    public ProximaNovaTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);

       applyCustomFont(context);
    } 

    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("proximanova_regular.otf", context);
        setTypeface(customFont);
    }
}

Y luego use esta clase personalizada en xml para TextView de la siguiente manera: -

   <com.myapp.customview.ProximaNovaTextView
        android:id="@+id/feed_list_item_name_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        />
 1
Author: Shubham Raitka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-10 06:51:48

Solo quiero mencionar que el infierno con las fuentes dentro de Android está a punto de terminar, porque este año en Google IO finalmente conseguimos esto - > https://developer.android.com/preview/features/working-with-fonts.html

Ahora hay un nuevo tipo de recurso a font y puede colocar todas las fuentes de su aplicación dentro de la carpeta res/fonts y acceder luego con R. font.my_custom_font, al igual que puede acceder a string valores res, drawable valores res, etc. Tienes incluso la posibilidad de crear font-face archivo xml, que se va a establecer de sus fuentes personalizadas (sobre cursiva, negrita y subrayado attr).

Lea el enlace de arriba para más información. Veamos el apoyo.

 1
Author: Sniper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 10:05:44

Aquí puedes ver todos los valores de la familia de fuentes disponibles y los nombres de los archivos de fuentes correspondientes(Este archivo se usa en Android 5.0+). En el dispositivo móvil, se puede encontrar en:

/system/etc/fonts.xml (para 5.0+)

(Para android 4.4 y versiones posteriores usando esta versión, pero creo que fonts.xml tiene un formato más claro y fácil de entender.)

Por ejemplo,

    <!-- first font is default -->
20    <family name="sans-serif">
21        <font weight="100" style="normal">Roboto-Thin.ttf</font>
22        <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
23        <font weight="300" style="normal">Roboto-Light.ttf</font>
24        <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
25        <font weight="400" style="normal">Roboto-Regular.ttf</font>
26        <font weight="400" style="italic">Roboto-Italic.ttf</font>
27        <font weight="500" style="normal">Roboto-Medium.ttf</font>
28        <font weight="500" style="italic">Roboto-MediumItalic.ttf</font>
29        <font weight="900" style="normal">Roboto-Black.ttf</font>
30        <font weight="900" style="italic">Roboto-BlackItalic.ttf</font>
31        <font weight="700" style="normal">Roboto-Bold.ttf</font>
32        <font weight="700" style="italic">Roboto-BoldItalic.ttf</font>
33    </family>

El atributo name name="sans-serif" de la etiqueta family definió el valor que puede usar en Android:fontFamily.

La etiqueta font define los archivos de fuentes correspondientes.

En este caso, puede ignorar la fuente bajo <!-- fallback fonts -->, que está utilizando para la lógica de reserva de las fuentes.

 0
Author: Gnod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-03 09:42:44

Utilizo Letter Press libpara mis cosas NonTextView como Botones y kianoni fontloader lib para mis TextViews la causa del uso del estilo en esta lib es más fácil que Letter Press para mí y obtuve retroalimentación ideal con eso. esto es ideal para aquellos que desean usar fuentes personalizadas, excepto la fuente Roboto. así que fue mi experiencia con font libs. para aquellos que quieran usar clase personalizada para cambiar la fuente, recomiendo crear esta clase con este snippet

public class TypefaceSpan extends MetricAffectingSpan {
/** An <code>LruCache</code> for previously loaded typefaces. */
private static LruCache<String, Typeface> sTypefaceCache =
        new LruCache<String, Typeface>(12);

private Typeface mTypeface;

/**
 * Load the {@link android.graphics.Typeface} and apply to a {@link android.text.Spannable}.
 */
public TypefaceSpan(Context context, String typefaceName) {
    mTypeface = sTypefaceCache.get(typefaceName);

    if (mTypeface == null) {
        mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                .getAssets(), String.format("fonts/%s", typefaceName));

        // Cache the loaded Typeface
        sTypefaceCache.put(typefaceName, mTypeface);
    }
}

@Override
public void updateMeasureState(TextPaint p) {
    p.setTypeface(mTypeface);

    // Note: This flag is required for proper typeface rendering
    p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}

@Override
public void updateDrawState(TextPaint tp) {
    tp.setTypeface(mTypeface);

    // Note: This flag is required for proper typeface rendering
    tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}

}

Y usar clase como esta

AppData = PreferenceManager.getDefaultSharedPreferences(this);
TextView bannertv= (TextView) findViewById(R.id.txtBanner);
    SpannableString s = new SpannableString(getResources().getString(R.string.enterkey));
    s.setSpan(new TypefaceSpan(this, AppData.getString("font-Bold",null)), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    bannertv.setText(s);

Tal vez esta ayuda.

 0
Author: Setmax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-03 10:21:59

Puede hacerlo de manera fácil mediante el uso de la siguiente biblioteca

Https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

Es ligero y fácil de implementar, simplemente copie sus fuentes en la carpeta de activos y use el nombre en xml.

 0
Author: Sanny Nagveker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-29 13:19:25

Prueba estos sencillos pasos. 1. crear carpeta de fuentes en la carpeta res. 2. copiar y pegar .archivo ttf en la carpeta de fuentes. 3. Ahora dar la ruta en xml como a continuación.

 android:fontFamily="@font/frutiger"

O lo que sea su nombre de archivo. Eso es código feliz

 0
Author: Syed Danish Haider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-26 05:30:16