How to change the font on the TextView?

前端 未结 16 731
清歌不尽
清歌不尽 2020-11-22 08:09

How to change the font in a TextView, as default it\'s shown up as Arial? How to change it to Helvetica?

相关标签:
16条回答
  • 2020-11-22 08:30

    First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView:

    Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
    textView.setTypeface(type);
    
    0 讨论(0)
  • 2020-11-22 08:30
    1. add class FontTextView.java:


    public class FontTextView extends TextView {
        String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};
    
        public FontTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(attrs);
        }
    
        public FontTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            if (!isInEditMode()) {
                init(attrs);
            }
    
        }
    
        public FontTextView(Context context) {
            super(context);
            if (!isInEditMode()) {
                init(null);
            }
        }
    
        private void init(AttributeSet attrs) {
            if (attrs != null) {
                TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
                if (a.getString(R.styleable.FontTextView_font_type) != null) {
                    String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];
    
                    if (fontName != null) {
                        Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                        setTypeface(myTypeface);
                    }
                    a.recycle();
                }
            }
        }
    }
    


    1. add to assets library font


    1. add to attrs.xml , The numbers should be in the order in array class.

      <declare-styleable name="FontTextView">
      <attr name="font_type" format="enum">
          <enum name="HelveticaNeue" value="0"/>
          <enum name="HelveticaNeueLight" value="1"/>
          <enum name="motschcc" value="2"/>
          <enum name="symbol" value="3"/>
      </attr>
      


    1. Select a font from the list
    0 讨论(0)
  • 2020-11-22 08:31

    First, the default is not Arial. The default is Droid Sans.

    Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.

    Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).

    EDIT

    The Android design language relies on traditional typographic tools such as scale, space, rhythm, and alignment with an underlying grid. Successful deployment of these tools is essential to help users quickly understand a screen of information. To support such use of typography, Ice Cream Sandwich introduced a new type family named Roboto, created specifically for the requirements of UI and high-resolution screens.

    The current TextView framework offers Roboto in thin, light, regular and bold weights, along with an italic style for each weight. The framework also offers the Roboto Condensed variant in regular and bold weights, along with an italic style for each weight.

    After ICS, android includes Roboto fonts style, Read more Roboto

    EDIT 2

    With the advent of Support Library 26, Android now supports custom fonts by default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here

    0 讨论(0)
  • 2020-11-22 08:32

    Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

    Check below link to check roboto fonts:

    How to use Roboto in xml layout

    Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        ......
        <item name="android:buttonStyle">@style/MyButton</item>
        <item name="android:textViewStyle">@style/MyTextView</item>
    </style>
    
    <style name="MyButton" parent="@style/Widget.AppCompat.Button">
        <item name="android:textAllCaps">false</item>
        <item name="android:fontFamily">sans-serif-light</item>
    </style>
    
    <style name="MyTextView" parent="@style/TextAppearance.AppCompat">
        <item name="android:fontFamily">sans-serif-light</item>
    </style>
    

    And don't forget to use 'AppTheme' in your AndroidManifest.xml

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        ......
    </application>
    
    0 讨论(0)
  • 2020-11-22 08:34

    I finally got a very easy solution to this.

    1. use these Support libraries in app level gradle,

      compile 'com.android.support:appcompat-v7:26.0.2'
      compile 'com.android.support:support-v4:26.0.2'
      
    2. then create a directory named "font" inside the res folder

    3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
    4. After that, reference that font from xml like this

              <Button
              android:id="@+id/btn_choose_employee"
              android:layout_width="140dp"
              android:layout_height="40dp"
              android:layout_centerInParent="true"
              android:background="@drawable/rounded_red_btn"
              android:onClick="btnEmployeeClickedAction"
              android:text="@string/searching_jobs"
              android:textAllCaps="false"
              android:textColor="@color/white"
              android:fontFamily="@font/times_new_roman_test"
              />
      

    In this example, times_new_roman_test is a font ttf file from that font directory

    0 讨论(0)
  • 2020-11-22 08:38

    Best practice ever

    TextViewPlus.java:

    public class TextViewPlus extends TextView {
        private static final String TAG = "TextView";
    
        public TextViewPlus(Context context) {
            super(context);
        }
    
        public TextViewPlus(Context context, AttributeSet attrs) {
            super(context, attrs);
            setCustomFont(context, attrs);
        }
    
        public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setCustomFont(context, attrs);
        }
    
        private void setCustomFont(Context ctx, AttributeSet attrs) {
            TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
            String customFont = a.getString(R.styleable.TextViewPlus_customFont);
            setCustomFont(ctx, customFont);
            a.recycle();
        }
    
        public boolean setCustomFont(Context ctx, String asset) {
            Typeface typeface = null;
            try {
                typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
            } catch (Exception e) {
                Log.e(TAG, "Unable to load typeface: "+e.getMessage());
                return false;
            }
    
            setTypeface(typeface);
            return true;
        }
    }
    

    attrs.xml: (Where to place res/values)

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="TextViewPlus">
            <attr name="customFont" format="string"/>
        </declare-styleable>
    </resources>
    

    How to use:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:foo="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <com.mypackage.TextViewPlus
            android:id="@+id/textViewPlus1"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:text="@string/showingOffTheNewTypeface"
            foo:customFont="my_font_name_regular.otf">
        </com.mypackage.TextViewPlus>
    </LinearLayout>
    

    Hope this will help you.

    0 讨论(0)
提交回复
热议问题