Как изменить шрифт textview android studio

How to add Custom Fonts in Android

Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. There are majorly three methods to add custom fonts to text in Android Studio. The first two methods involve the use of the Typeface class while the last method is quite direct and easy. Follow the entire article to explore all the methods.

Method 1

In this method, we’ll first download the font’s ttf file from the internet and then use them as an asset or a resource to set the Typeface. You may find the downloadable fonts here. Here Dancing Script font is used. Once you download the fonts of your choice, unzip the folder and copy the font file. By creating a new Android resource directory:

  • Step 1: In the project’s resource folder, create a new Android Resource Directory of Resource type: font and paste this ‘ttf’ file here. Note that while pasting it, keep in mind that a resource file’s name can consist of lower-case letters and underscores only, so refactor the file accordingly.
  • Step 2: Create the layout in the XML files.
  • Step 3: Now in the MainActivity(necessarily the Activity corresponding to the layout file where the TextView to be customised lies), set the typeface for that TextView.
  • Output:

By creating a new asset folder:

  • Step 1: Create a new asset folder(app/New/Folder/Asset folder) in Android Studio and paste the ‘ttf’ file of the font here. The picture on the left shows how to add the assets folder to the project whereas the picture on the right shows the added ‘ttf’ file to it.
  • Step 2: While we keep the XML layout to be same as earlier, the Java code of the MainActivity is modified this way.
  • Output: />

Method 2

In this method we’ll create a separate java class dediacted to a particular font and use this class instead of the conventional TextView tag in the XML file.

  • Step 1: Download the font of your choice and use either of the above two approaches to store it in the project. I have pasted my file in the assets folder.
  • Step 2: Create a new Java file in the package. Preferably name it according to the font that you want to implement. Here we have created a file named CalligraffittiRegular.
  • Step 3: Extend the following class in this Java file:
  • Step 4: Complete the Java code by adding the required constructors.
  • Step 5: Create a method in the class wherein the typeface for the font is set.
  • Step 6: Call this method in each constructor. Refer to the following code for a better understanding.
  • Step 7: Now in your XML layout file, use this font class instead of the conventional TextView tag.
  • Output: />

Method 3

With Android 8.0 (API Level 26) a simpler method was introduced for using fonts as a resource in Android Studio. The android:fontFamily attribute of the TextView class is used to specify the font.

  • Step 1: Go to the XML file and go to the Design view.
  • Step 2: Click the TextView you want to change the font of.
  • Step 3: In the search bar, search for fontFamily.
  • Step 4: In the dropdown menu, you can check out the fonts available. In case you want to explore more, scroll down and click ‘More Fonts…‘.
  • Step 5: A dialog box pops up. Choose a font of your choice, choose the style you like in the preview, and click OK.
  • Step 6: This would create a downloadable font and add it automatically to your project. The following files automatically get added to your project:
  • Step 7: Now the XML file will be look like:
  • Output:

Changing the Font for Android TextViews and EditTexts

Setting a new font when developing an Android app puts your own style onto the user interface (UI), and can help it stand out from the crowd. This article shows how easy it is to change Android TextView and EditText fonts using properties. Assigning a custom font in code from the app’s assets is also covered in the Using a Custom Font section.

(This Android font example assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

Easy Font Modifications to Get Different Text Styles in Android

For many Activity screens the interface is usually constructed using Android layouts and interface widgets. The interface widgets, such as CheckBoxes and TextViews, have various properties that can be easily modified to change their look. Changing properties can be done via:

  • The Properties list when viewing an Activity in the Design (graphical layout) screen in Studio.
  • By editing the layout XML directly in the Text view.
  • Or by using code to set property values.

Properties in Android Studio

Follow this article as a tutorial by starting a new Android project in Studio. Here the project is called Fonts and uses an Empty Activity. All other settings are left at their default values.

Edit the Text Properties with the Android Studio’s Graphical Layout

The new Android Studio project will have an activity_main.xml as the starting layout. With the Design mode open select the Hello World! TextView . With a TextView selected its properties can be changed in the Properties pane. Increase the textSize to better see the changes you make to the properties.

For the TextView find the typeface property and try the various settings of normal, sans, serif, and monospace. Add several TextViews to the screen each set to a different typeface value to compare them. The typeface property is stored in the XML layout file as the TextView’s attribute android:typeface.

android:typeface Properity

Having no typeface set (the android:typeface attribute is not present) or having it set to normal or sans results in the same font style. This is because the default (normal) font setting uses the sans value. The monospace setting provides a font in which each letter takes up an equal amount of screen space (unlike the other settings in which the space a letter takes up various depending upon the letter, so i’s are a lot narrower than w’s).

A serif font is one that has additional decoration at the end of the strokes that make up the letter. As this picture based on the Wikipedia entry for serif shows. The name of the sans setting comes from the phrase sans serif which means without serif as sans is french for without.

Comparing Sans Serif and Serif fonts

Update to Android with the fontFamily Attribute

For more control of the fonts used by Views a fontFamily attribute is supported. This also allows loading of fonts from a res/font folder instead of using other resources as described in Using a Custom Font further on in the article. Try the various fontFamily settings of sans-serif, sans-serif-condensed, serif, monospace, serif-monospace, casual, cursive and sans-serif-small-caps. The sans-serif value is the same as typeface sans.

android:fontFamily Properity

Note: Older versions of Android will not support fontFamily. A fontFamily not present on the system, i.e. not available to typeface, will fall back to the default typeface attribute setting (sans).

Bold and Italic with or without All Caps

Use the textStyle Property to add bold, italic, or bold and italic options to the text (in the layout XML the android:textStyle attribute). The default value is normal, the value it takes if no textStyle is set. The other values are bold and italic, either individually or combined with a bar, as in android:textStyle=»bold|italic» .

The textAllCaps property (in XML android:textAllCaps ) is set true for all capital letters (false or not present for normal text, the default setting).

Android bold and italic text

Combining Properties into a Text Appearance

When putting together an app’s design you may have several Views that you want to set with the same properties (such as text color and text size). Setting the properties on all the Views individually becomes a chore with many Views in an app, especially if you decide to change a property later and have to find each View to edit the property. Fortunately Android can group properties into styles, a style is then applied to a View with one property. Then you only need to edit style properties in a single location, similar to the way HTML web pages are styled with cascading style sheets (CSS). As for CSS styles can themselves use other defined styles.

Styles that only modify a View’s text properties is applied with the textAppearance property (XML attribute android:textAppearance ). Styles that modify non-text properties are applied via the style property. This tutorial will only include a brief introduction to styles.

Android textAppearance Property

Change the textAppearance property of a TextView to AppCompat.Large, the full value is @style/TextAppearance.AppCompat.Large, in the XML:

This says it is pointing to an Android style attribute called TextAppearance.AppCompat.Large. You can see this attribute in the appcompat library in the project tree. The source is under the folder where the Android SDK was installed:

The styles.xml has:

The parent is in:

This gives an idea on how to styles are built up and referenced.

Using a Style Resource

Use a style to add bold and serif to a text view. To add a styles file select the res folder in the Project tree and using the Files menu or context menu (normally right-click) select New then XML and then Values XML File. Give it a name, here mytextstyle was used to create mytextstyle.xml. (Styles do not need to be in a file named styles.xml, they can be stored in any named resource file). Click the finish button. In the new opened XML file define a new style for bold and serif, the textSize is set to 18sp to override the small default font size.

Set the textAppearance of a TextView to this new style android:textAppearance=»@style/MySerifBold» .

Instead of setting the textSize to 18sp an existing large style code be set as the parent:

Using a Style

Font Size Measurements in Android

When it comes to sizing text for display in an Activity there are several factors to consider, the size needed for easy reading, the size and resolution of the screen, and the user’s font size device setting. The size of text has traditionally been based on the point. This is a unit of measurement originating from the physical printing process. There are 72 points to an inch so a 12 point font will produce a line of text one sixth of an inch, about 4.2mm, high (12/72=1/6). Word processing software still uses this measurement with the font size of the text entered or selected under the font formatting options as a simple number (usually selectable from a range such as 8, 9, 10, 11, 12, 14, 16 and so on).

Font Sizes

Android supports the point size (pt) but it is a bit cumbersome for mobile device screens. Android devices come in all sorts of screen sizes and resolutions. The screen density of a device is usually stated in dots per inch (DPI). This is the number of pixels that a screen contains in one inch. A 240 DPI screen has a lower resolution than a 320 DPI screen. Font sizes can be set using pixel measurements (px) but this leads to different size texts on different screen densities even though the screens may be similar in size physically. A 3 inch wide 240 DPI screen would have larger text than on a 3 inch wide 320 DPI when sizing font using pixel values. To allow for this Android provides the density pixel (dp) setting and sizes set using dp are scaled correctly for different DPIs. However, dp does not cater for a user’s font size setting.

Android Accessibility

Android devices can help those with poor eyesight by allowing them to increase the font size setting on their devices (or decrease it for the keen-sighted). Depending upon the version of Android the default text size can be bumped up or down one or more sizes. You Apps should also cater for this setting by defining Text Size using scaled pixels (sp). As the user changes their device font settings so the text in your Activity would scale appropriately if sp is used.

Android Text Sizes

Using a Custom Font

The fonts bundled with Android do not give a great deal of choice. Fortunately Android supports any TrueType font. The font file is added to the project then loaded into a Typeface object and assigned to the widget. (See also the new fontFamily attribute.) You could use a font bundled with your development PC (for example on Windows from the C:\Windows\Fonts folder), or one you purchased, though there may be licensing issues. There are lots of free fonts available. In this example we are using the Strato free font from the Font Library website. Download the font and extract the .ttf (TrueType) files from the strato.zip file.

Strato font

The Strato-linked.ttf file is copied to the src/main/assets folder. (To create an assets folder highlight the app in the Project explorer and use the File or context menu. Select New then Folder then Assets Folder.) Open the MainActivity.java. Just before the closing brace of the onCreate method a Typeface object is created and loaded with a font from assets. It is then assigned to a TextView or EditText using the setTypeface method:

Ideally this needs to be wrapped in an exception handler incase the TTF file is corrupt or the name is misspelt. If you are using text characters outside of the typical text range ensure that the font chosen contains those characters.

Custom Font on Android

Using the Android Fonts on Your PC

The fonts shipped with Android are placed onto you PC when the SDK is installed. Look in android-sdk\platforms\android-x\data\fonts (where x is the API level), these fonts can be installed onto your PC and used in your word processor, useful when doing app design documents.

A Final Word on Fonts

This tutorial has given a brief overview on how to use different fonts in an Android Activity, you can also use color, spacing and borders to improve Activity layouts. As well as the Font Library mentioned above, the Wikipedia article Open-source Unicode typefaces is a good source of information on a variety of royalty free fonts. A demo project featuring the techniques used in this tutorial is available to download in the fonts.zip file ready for importing into Android Studio. Instructions are included in the zip and also on the the Android Example Projects page.

See Also

  • Android Styles and Themes on the Android Developers website.
  • Download the code for this example, available in fonts.zip
  • For more tutorials in Studio see the Android Example Projects page.
  • For a full list of all the articles in Tek Eye see the full site Index.

Archived Comments

Nitin on January 7, 2013 at 10:09 am said: I want to apply Comic-sans to my whole android application but not got it can you please help me?

Tek Eye on January 7, 2013 at 4:27 pm said: The Comic Sans MS files (comic.ttf and comicbd.ttf) are usually in the C:\Windows\Fonts folder on a PC. Unfortunately Comic Sans can not be distributed because of licensing (see https://www.microsoft.com/typography/faq/faq11.htm). Use an alternative similar free font, for example one listed at https://www.fontsquirrel.com/fonts/list/style/Comic

Sulaiman Khan on June 5, 2013 at 10:13 am said: Nice, a very very informative article.

Melissa on December 17, 2013 at 12:26 pm said: I am brand new to the Android app development world. When I add textview objects to my layout page, the only property that I am allowed to change is the text. I can’t change font size, style, etc. Any ideas on what is wrong with my setup? I can’t do it on any app that I create.

Tek Eye on December 17, 2013 at 2:04 pm said: Changing the properties of a selected item should be straightforward. Are you using Eclipse with the Android SDK or Android Studio? If you can’t change values using the Properties list on the Outline tab (use the Window then Show View menu if it is not shown) can you edit the XML layout file directly? (Click the layout file name next to the Graphical Layout tab to see the raw XML). Add a property in the XML to see if the item changes, e.g. add textStyle="bold" to bold the text:

When you create a new app and does it run OK? (see Your First Android Hello World Java Program). Can you change the default app screen?

Melissa on December 18, 2013 at 12:31 pm said: I am using Eclipse with the Android SDK or Android Studio? I can edit the XML layout file directly? The app runs fine! I am working with 15 students and it works perfect on about 11 of the devices, but the other 4 can’t modify the properties in the graphical layout. Once I enter the code on the XML layout file, then it lets them modify that setting on the properties dialog box.

Tek Eye on December 18, 2013 at 4:58 pm said: I’ve not seen that behaviour before. I checked the Android project issue tracker and someone has reported a similar issue (62792). I suggest you add your experience to the bug report so that Android has as much information as possible so solve the issue.

Published: 2012-11-06 Updated: 2017-05-29

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Working with the TextView

Every Android device comes with a collection of standard fonts: Droid Sans, Droid Sans Mono and Droid Serif. They were designed to be optimal for mobile displays, so these are the three fonts you will be working with most of the time and they can be styled using a handful of XML attributes. You might, however, see the need to use custom fonts for special purposes.

This guide will take a look at the TextView and discuss common properties associated with this view as well as how to setup custom typefaces.

Text Attributes

Typeface

As stated in the overview, there are three different default typefaces which are known as the Droid family of fonts: sans , monospace and serif . You can specify any one of them as the value for the android:typeface attribute in the XML:

Here’s how they look:

fonts

In addition to the above, there is another attribute value named «normal» which defaults to the sans typeface.

Text Style

The android:textStyle attribute can be used to put emphasis on the text. The possible values are: normal , bold , italic . You can also specify bold|italic .

A sampling of styles can be seen below:

style

Text Size

android:textSize specifies the font size. Its value must consist of two parts: a floating-point number followed by a unit. It is generally a good practice to use the sp unit so the size can scale depending on user settings.

A sampling of styles can be seen below:

style

Too many type sizes and styles at once can wreck any layout. The basic set of styles are based on a typographic scale of 12, 14, 16, 20, and 34. Refer to this typography styles guide for more details.

Text Truncation

There are a few ways to truncate text within a TextView . First, to restrict the total number of lines of text we can use android:maxLines and android:minLines :

In addition, we can use android:ellipsize to begin truncating text

Following values are available for ellipsize : start for . bccc , end for aaab. , middle for aa. cc , and marquee for aaabbbccc sliding from left to right. Example:

style

There is a known issue with ellipsize and multi-line text, see this MultiplelineEllipsizeTextView library for an alternative.

Text Color

The android:textColor and android:textColorLink attribute values are hexadecimal RGB values with an optional alpha channel, similar to what’s found in CSS:

The android:textColorLink attribute controls the highlighting for hyperlinks embedded within the TextView. This results in:

We can edit the color at runtime with:

Text Shadow

You can use three different attributes to customize the appearance of your text shadow:

  • android:shadowColor — Shadow color in the same format as textColor.
  • android:shadowRadius — Radius of the shadow specified as a floating point number.
  • android:shadowDx — The shadow’s horizontal offset specified as a floating point number.
  • android:shadowDy — The shadow’s vertical offset specified as a floating point number.

The floating point numbers don’t have a specific unit — they are merely arbitrary factors.

This results in:

Various Text Properties

There are many other text properties including android:lineSpacingMultiplier , android:letterSpacing , android:textAllCaps , android:includeFontPadding and many others:

android:includeFontPadding removes the extra padding around large fonts. android:lineSpacingMultiplier governs the spacing between lines with a default of «1».

Inserting HTML Formatting

TextView natively supports HTML by translating HTML tags to spannable sections within the view. To apply basic HTML formatting to text, add text to the TextView with:

This results in:

Note that all tags are not supported. See this article for a more detailed look at supported tags and usages.

Setting Font Colors

For setting font colors, we can use the <font> tag as shown:

And you should be all set.

Storing Long HTML Strings

If you want to store your HTML text within res/values/strings.xml , you have to use CDATA to escape such as:

and access the content with getString(R.string.htmlFormattedText) to load this within the TextView.

For more advanced cases, you can also check out the html-textview library which adds support for almost any HTML tag within this third-party TextView.

Autolinking URLs

TextView has native support for automatically locating URLs within the their text content and making them clickable links which can be opened in the browser. To do this, enable the android:autolink property:

This results in:

Issues with ListView

One known issue when using android:autoLink or the Linkify class is that it may break the ability to respond to events on the ListView through setOnItemClickListener . Check out this solution which extends TextView in order to modify the onTouchEvent to correctly propagate the click. You basically need to create a LinkifiedTextView and use this special View in place of any of your TextView’s that need auto-link detection.

In addition, review these alternate solutions which may be effective as well:

  • This stackoverflow post or this other post
  • This android issue for additional context.

Displaying Images within a TextView

A TextView is actually surprisingly powerful and actually supports having images displayed as a part of it’s content area. Any images stored in the «drawable» folders can actually be embedded within a TextView at several key locations in relation to the text using the android:drawableRight and the android:drawablePadding property. For example:

Which results in:

Contacts View

In Android, many views inherit from TextView such as Button s, EditText s, RadioButton s which means that all of these views support the same functionality. For example, we can also do:

Which results in:

EditText with drawable

The relevant attributes here are drawableLeft , drawableRight , drawableTop and drawableBottom along with drawablePadding . Check out this TextView article for a more detailed look at how to use this functionality.

Note that if you want to be able to better control the size or scale of the drawables, check out this handy TextView extension or this bitmap drawable approach. You can also make calls to setCompoundDrawablesWithIntrinsicBounds on the TextView .

Using Fonts

The easiest way to add font support is to upgrade to Android Studio 3.0, which provides the ability to use other fonts provided by Google. You can visit https://fonts.google.com/ to see the ones that are free to use. See the FAQ section for more information.

Android Studio v3.0 provides built-in support for these fonts and will automatically handles generating the XML and necessary metadata. Next to the Attributes section of a TextView , look for the fontFamily and click on More Fonts :

More fonts

You will then see these choices:

Fonts

Once you choose a font, you will notice that a font directory will be created and a similar XML file will be generated. Notice that Android Studio automatically takes care of adding the necessary font provider certificates required to request from Google:

Adding custom fonts

We can actually use any custom font that we’d like within our applications. Check out fontsquirrel for an easy source of free fonts. For example, we can download Chantelli Antiqua as an example.

Fonts are stored in the «assets» folder. In Android Studio, File > New > folder > Assets Folder . Now download any font and place the TTF file in the assets/fonts directory:

We’re going to use a basic layout file with a TextView , marked with an id of «custom_font» so we can access it in our code.

To set the custom font manually, open your activity file and insert this into the onCreate() method:

Alternatively, you can use the third-party calligraphy library:

Either method will will result in:

custom

You’ll also want to keep an eye on the total size of your custom fonts, as this can grow quite large if you’re using a lot of different typefaces.

Using Spans to Style Sections of Text

Spans come in really handy when we want to apply styles to portions of text within the same TextView. We can change the text color, change the typeface, add an underline, etc, and apply these to only certain portions of the text. The full list of spans shows all the available options.

As an example, let’s say we have a single TextView where we want the first word to show up in red and the second word to have a strikethrough:

Custom

We can accomplish this with spans using the code below:

Note: There are 3 different classes that can be used to represent text that has markup attached. SpannableStringBuilder (used above) is the one to use when dealing with mutable spans and mutable text. SpannableString is for mutable spans, but immutable text. And SpannedString is for immutable spans and immutable text.

Android и кастомные шрифты или «Да здравствует API 26»

Если было много view где требовались нестандартные шрифты, то мы использовали что-то вроде такого:

view.xml
CustomFontTextView.class

И это я пропустил огромный кусок который отвечает за то, чтобы не писать каждый раз путь к шрифту, а указывать

Ну, или шли на гитхаб и в результате находили Calligraphy (7000 звезд!)

Ни для кого не секрет что этот подход содержал много минусов как в огромном количестве boilerplate кода, так и в том, чтобы сделать это эффективно и где-нибудь не утечь по памяти запрашивая каждый раз Typeface.

Но все изменилось в API 26

Похоже, гугл наконец-то сдался и решил отказаться от навязывания Roboto и сделал удобное подключение сторонних шрифтов, за что ему огромное спасибо.

Линк для тех, кто любит читать в оригинале.

Теперь подключение состоит всего из нескольких несложных шагов:

1. Создаем папку font в res
Resource type выбираем font

image

2. Перетаскиваем в новую папку все нужные нам в проекте шрифты

3. Создаем файл для семейства шрифтов.

Обратите внимание: я сразу добавил в пример то как должен выглядеть файл, если вы хотите поддерживать и более старые версии Андроида. (Начиная с 14). Если вам повезло и у вас таргет только на супер-новые девайсы, то ваш файл сократится в 2 раза

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *