Jak zmienić fontFamily TextView w Androidzie

Więc chciałbym zmienić android:fontFamily W Androidzie, ale nie widzę żadnych predefiniowanych czcionek w Androidzie. Jak wybrać jeden z predefiniowanych? Nie muszę definiować własnego kroju pisma, ale potrzebuję tylko czegoś innego niż to, co teraz pokazuje.

<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"
 />
Wygląda na to, że to, co tam zrobiłem, nie zadziała! BTW android:fontFamily="Arial" to była głupia próba!
Author: Piyush, 2012-08-26

25 answers

Z Androida 4.1 / 4.2 / 5.0, dostępne są następujące rodziny czcionekRoboto:

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)

Tutaj wpisz opis obrazka

W połączeniu z

android:textStyle="normal|bold|italic"

Możliwe jest 16 wariantów:

  • Roboto regular
  • Roboto italic
  • Roboto bold
  • Roboto bold italic
  • Roboto-Light
  • Roboto-Light italic
  • Roboto-Cienki
  • Roboto-cienka italic
  • Roboto-Skondensowany
  • Roboto-Condensed italic
  • Roboto-Condensed bold
  • Roboto - Condensed bold italic
  • Roboto-Black
  • Roboto-Black italic
  • Roboto-Medium
  • Roboto-Medium italic

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-18 13:58:54

Oto sposób programowania czcionki:

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

Umieść plik czcionki w folderze zasoby. W moim przypadku utworzyłem podkatalog o nazwie fonts.

EDIT: Jeśli zastanawiasz się, gdzie jest Twój folder zasobów zobacz to pytanie

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:48

[[4]}musiałem przeanalizować /system/etc/fonts.xml w niedawnym projekcie. Oto obecne rodziny czcionek od 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              ║
╚════╩════════════════════════════╩═════════════════════════════╝

Oto parser (oparty na 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;
        }

    }
}

Możesz użyć powyższej klasy w swoim projekcie. Na przykład możesz dać użytkownikom wybór rodzin czcionek i ustawić krój pisma zgodnie z ich preferencjami.

Mały niekompletny przykład:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-09 10:25:46

Począwszy od Android-Studio 3.0 bardzo łatwo zmienić rodzinę czcionek

Korzystanie z biblioteki wsparcia 26, będzie działać na urządzeniach z systemem Android API w wersji 16 i wyższej

Utwórz folder font w katalogu res.Pobierz dowolną czcionkę i wklej ją do folderu font. Struktura powinna być taka jak poniżej

Proszę.

Teraz możesz zmienić czcionkę w układzie używając

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

To Zmień programowo

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

Aby zmienić czcionkę za pomocą stylów .XML tworzenie stylu

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

I zastosuj ten styl do TextView

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

Możesz również utworzyć własną rodzinę czcionek

- kliknij prawym przyciskiem myszy folder czcionek i przejdź do New > Font Resource file . Pojawi się nowe okno pliku zasobów.

- wprowadź nazwę pliku , a następnie kliknij OK. Nowy font resource XML otwiera się w edytorze.

Napisz tutaj własną rodzinę czcionek, na przykład

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

Jest to po prostu mapowanie określonego stylu czcionki i wagi czcionki do zasobu czcionki, który zostanie użyty do renderowania tego konkretnego wariantu. Poprawne wartości dla fontStyle to normal lub italic; a fontWeight jest zgodny ze specyfikacją CSS font-weight

1.to Zmień fontfamily w layout możesz napisać

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

2. To Zmień Programowo

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

Uwaga: od wersji Android Support Library 26.0 należy zadeklarować oba zestawy atrybutów (android: i app:), aby upewnić się, że czcionki są ładowane na uruchomionych urządzeniach Api 26 lub niższe.

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

Aby zmienić czcionkę całej aplikacji Dodaj te dwie linie w 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>

Zobacz dokumentację , Android Custom Fonts Tutorial aby uzyskać więcej informacji

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-04 06:17:33

Android nie pozwala na ustawianie niestandardowych czcionek z układu XML. Zamiast tego należy spakować określony plik czcionki w folderze zasobów aplikacji i ustawić go programowo. Coś w stylu:

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

Zauważ, że możesz uruchomić ten kod dopiero po wywołaniu metody setContentView (). Ponadto tylko niektóre czcionki są obsługiwane przez system Android i powinny być w formacie .ttf (TrueType) lub .otf (OpenType). Nawet wtedy niektóre czcionki mogą nie działać.

Ta jest czcionką, która zdecydowanie działa na Androidzie i możesz użyj tej opcji, aby potwierdzić, że kod działa na wypadek, gdyby plik czcionki nie był obsługiwany przez system Android.

Aktualizacja Androida O: jest to teraz możliwe dzięki XML w Androidzie o , na podstawie komentarza Rogera.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-26 13:25:37

To to samo co android:typeface.

Wbudowane czcionki to:

  • normal
  • sans
  • serif
  • monospace

Zobacz android: typeface .

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-26 07:41:59

Aby ustawić Roboto programowo:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-06 22:59:40

Jeśli chcesz go programowo, możesz użyć

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

Gdzie SANS_SERIF możesz użyć:

  • DEFAULT
  • DEFAULT_BOLD
  • MONOSPACE
  • SANS_SERIF
  • SERIF

I gdzie ITALIC możesz użyć:

  • BOLD
  • BOLD_ITALIC
  • ITALIC
  • NORMAL

Wszystko jest podane na deweloperów Androida

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-28 19:39:10

Używam doskonałej biblioteki kaligrafii autorstwa Chrisa Jenxa zaprojektowanej, aby umożliwić korzystanie z niestandardowych czcionek w aplikacji na Androida. Spróbuj!

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-06 13:50:38

To, czego chcesz, nie jest możliwe. Musisz ustawić TypeFace w swoim kodzie.

In XML to co możesz zrobić to

android:typeface="sans" | "serif" | "monospace"

Inne to nie można dużo grać z czcionkami w XML. :)

Dla Arial Musisz ustawić typ twarzy w kodzie.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-26 07:38:37

Łatwym sposobem zarządzania czcionkami byłoby zadeklarowanie ich za pomocą zasobów, jako takich:

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

Jest to oparte na kodzie źródłowymProszę. Oraz Proszę.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-23 21:52:04

Dynamicznie możesz ustawić fontfamily podobny do android: fontFamily w xml używając tego,

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

Oto lista domyślna czcionka rodzina używana, użyj dowolnego z tych znaków, zastępując podwójny łańcuch cudzysłowów "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 " jest plikiem ttf. ścieżka będzie w src / assets/fonts / mycustomfont.ttf , możesz dowiedzieć się więcej o domyślnej czcionce w tej domyślnej rodzinie czcionek
 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-26 13:03:49

Stworzyłem małą bibliotekę o nazwie Foundry, której możesz użyć do stosowania własnych krojów pisma za pomocą układów i stylów 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 08:10:18

Metodą prób i błędów dowiedziałem się, co następuje.

Wewnątrz *.xml możesz łączyć czcionki stockowe z następującymi funkcjami, nie tylko z krojem pisma:

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

W przypadku tych dwóch stylów nie było potrzeby używania kroju pisma w żadnym innym przypadku. Zakres kombinacji jest znacznie większy z 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-08 10:17:21

Poprawna wartość Androida: fontFamily jest zdefiniowana w /system / etc / system_fonts.xml (4.x) lub / system / etc / fonts.xml (5.x). Jednak producent urządzenia może go zmodyfikować, więc rzeczywista czcionka użyta przy ustawianiu wartości fontFamily zależy od wyżej wymienionego pliku podanego urządzenia.

W AOSP czcionka Arial jest poprawna, ale musi być zdefiniowana za pomocą "arial", a nie "Arial", na przykład android: fontFamily= "arial" . Zobacz też: 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>

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

Istnieją trzy odpowiednie atrybuty xml do definiowania "czcionki" w układzie-- android: fontFamily, android: typeface i android: textStyle . Kombinacja "fontFamily" i "textStyle" lub "krój pisma" i "textStyle" może być używana do zmiany wyglądu czcionki w tekście, tak samo jak sama. Fragment kodu w widoku tekstowym .java Jak to:

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

Z kodu możemy zobaczyć:

  1. Jeśli ustawiona jest "fontFamily" , to "krój pisma" zostanie zignorowany.
  2. "krój pisma" ma standardowe i ograniczone ważne wartości. W rzeczywistości wartości są "normalne ""sans ""serif" i "monospace", można je znaleźć w system_fonts.xml (4.x) lub czcionek.xml (5.x). W rzeczywistości zarówno "normal", jak i "sans" są domyślną czcionką systemu.
  3. "fontFamily" może być używany do ustawiania wszystkich czcionek wbudowanych czcionek, podczas gdy "krój pisma" zapewnia tylko typowe czcionki "sans-serif "" serif "i" monospace " (trzy główne kategorie typu czcionki na świecie).
  4. gdy ustawiamy tylko "textStyle", ustawiamy domyślną czcionkę i określony styl. Wartość efektywna to "normal ""bold ""italic" i "bold | italic".
 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-19 07:33:44

Jest to również dobra biblioteka RobotoTextView . To naprawdę służy twoim potrzebom.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-13 10:56:10

Ustawiasz styl w res/layout/value/style.xml Tak:

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

I aby użyć tego stylu w pliku main.xml Użyj:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-01 13:44:43

Oto łatwiejsze wa y, które mogą działać w niektórych przypadkach. Zasadą jest dodanie niewidocznego TextVview w układzie xml i uzyskanie jego kroju pisma w kodzie Javy.

Układ w pliku 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"/>

Oraz kod Javy:

myText.setTypeface(textViewSelectedDescription.getTypeface());

Zadziałało dla mnie (na przykład w Textswitcherze).

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-09 09:47:41

Jeśli chcesz używać TextView w tak wielu miejscach z tą samą rodziną czcionek, rozszerz klasę TextView i ustaw czcionkę w następujący sposób: -

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

A następnie użyj tej niestandardowej klasy w xml dla TextView w następujący sposób: -

   <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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-10 06:51:48

Chcę tylko wspomnieć, że piekło z czcionkami w Androidzie zaraz się skończy, bo w tym roku na Google IO w końcu mamy to - > https://developer.android.com/preview/features/working-with-fonts.html

Teraz istnieje nowy typ zasobu a font i możesz umieścić wszystkie czcionki aplikacji w folderze res / fonts i uzyskać do nich dostęp za pomocą R. font. my_custom_font, tak jak możesz uzyskać dostęp do stringwartości res, drawable wartości res itp. Masz nawet możliwość stworzenia pliku font-face xml, który będzie zestawem własnych czcionek (o kursywie, pogrubieniu i podkreśleniu attr).

Przeczytaj powyższy link, aby uzyskać więcej informacji. Zobaczmy wsparcie.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-02 10:05:44

Tutaj możesz zobaczyć wszystkie dostępne wartości fontFamily i odpowiadające im nazwy plików czcionek(ten plik jest używany w Androidzie 5.0+). W urządzeniu mobilnym można go znaleźć w:

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

(dla Androida 4.4 i poniżej przy użyciu Ta wersja, ale myślę, że fonts.xml ma bardziej przejrzysty format i łatwy do zrozumienia.)

Na przykład,

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

Atrybut name name="sans-serif" znacznika family zdefiniował wartość, której możesz użyć w android:fontFamily.

Znacznik font definiuje odpowiednie pliki czcionek.

W tym przypadku możesz zignorować źródło Pod <!-- fallback fonts -->, które jest używane do logiki zapasowej czcionek.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-03 09:42:44

Używam Letter Press lib dla moich rzeczy NonTextView, takich jak Buttons i kianoni fontloader lib {[4] } dla moich TextView przyczyna użycia stylu w tej lib jest dla mnie łatwiejsza niż Letter Press i dostałem idealną opinię z tym. jest to świetne dla tych, którzy chcą używać niestandardowej czcionki z wyjątkiem czcionki Roboto. więc to było moje doświadczenie z libs czcionek. dla tych, którzy chcą użyć niestandardowej klasy do zmiany czcionki, polecam utworzyć tę klasę z tym 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);
}

}

I użyj takiej klasy

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);
Może to pomoże.
 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-03 10:21:59

Możesz to zrobić w prosty sposób, używając poniższej biblioteki

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

Jest lekki i łatwy do wdrożenia, wystarczy skopiować czcionki w folderze zasobów i użyć nazwy w 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-29 13:19:25

Wypróbuj te proste kroki. 1. utwórz folder czcionek w folderze res. 2. Kopiuj i wklej .plik ttf do folderu czcionek. 3. Teraz podaj ścieżkę w xml jak poniżej.

 android:fontFamily="@font/frutiger"

Albo jaka jest Twoja nazwa pliku. Thats it happy code

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 05:30:16