开发者

Set font at runtime, TextView

How to set the font of a TextView created at runtime?

I cr开发者_如何学Pythoneated a TextView

Textview tv = new TextView(this);      
tv.setTextSize(20);

I can easily change the size, now I'd like to set font style to "Verdana".

How to do this?


To set In-built Font at Run-Time:

  • First of all, To Change Font-face, a Typeface class is used.

  • Now, at Run-Time, to set the font-face, Use setTypeface(Typeface) from the Java code

  • at Design-Time, to set the font-face, Use android:typeface="serif"

For example:

<TextView android:text="@+id/TextView01"
 android:id="@+id/TextView01"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="30px"
 android:textStyle="italic"
 android:typeface="serif" />

To set Custom font(s) in your Android application

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there:

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


You can have .ttf font in your asset folder. Say font's name is "default.ttf" and you just now have to write below 2 lines of code

TextView text = new TextView(this);
text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf"));

You must also we careful because different font have different sizes. You may need to set size as :

text.setTextSize(20);


you can use your font which you have store in font "res/font" ex. for API level 16 and above.

   Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
   txtView.setTypeface(typeface);

you can also use

   Typeface typeface = getResources().getFont(R.font.rubik_medium);
   txtView.setTypeface(typeface);

but it support with API level 26 and above.


With introduction of Fonts in XML in Android 8.0 (backward compatible from API version 14) its very easy to set font from xml itself.

From the android documentation:

Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

Firstly create a Android Resource Directory in res folder named as font
Add your .ttf font file to that directory, and then create font family

Create a font family

A font family is a set of font files along with its style and weight details. In Android, you can create a new font family as an XML resource and access it as a single unit, instead of referencing each style and weight as separate resources. By doing this, the system can select the correct font based on the text style you are trying to use.

To create a font family, perform the following steps in the Android Studio:

  1. Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
  2. Enter the file name, and then click OK. The new font resource XML opens in the editor.
  3. Enclose each font file, style, and weight attribute in the <font> element. The following XML illustrates adding font-related attributes in the font resource XML:

    <?xml version="1.0" encoding="utf-8"?> <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>

Then use the following code to set font in your textView like

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


Here is a small utility class

public class TypefaceHelper {

    public static void setViewGroupTypeface(ViewGroup container, Typeface typeface) {
        final int children = container.getChildCount();

        for (int i = 0; i < children; i++) 
            View child = container.getChildAt(i);

            if (child instanceof TextView) {
                setTextViewTypeface((TextView) child, typeface);
            } else if (child instanceof ViewGroup) {
                setViewGroupTypeface((ViewGroup) child, typeface);
            }
        }
    }

    public static void setTextViewTypeface(TextView textView, Typeface typeface) {
        textView.setTypeface(typeface);
    }

}

For things like Spinners or ListViews (i.e. any kind of AdapterView) which generate their children from an adapter you will need to set the typeface of each item View in the getView (or similar) method of the adapter. This is because views may be created as needed and so setting the Typeface in onCreate won't work properly.


Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,

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

These are the list of default font family used, use any of this by replacing the double quotation string "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" is the ttf file. Path will be in src/assets/fonts/mycustomfont.ttf


If you don't want to use typeface and fiddle around with the path to your font file (Which may crash your application if you put in an incorrect path), here's another way.

First create a style in your styles.xml

<style name="YourFont">
    <item name="android:fontFamily">@font/your_font</item>
</style>

Then you can just add the style using

textView.setTextAppearance(context, R.style.YourFont);


You need to use Typeface:

  1. add font you wish to use to your project as asset.
  2. create Typeface object using that font:

    Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");

  3. set typeface to the object you'd like to customize:

    TextView myTextView = (TextView)findViewById(R.id.my_text_view); myTextView.setTypeface(myFont);


You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont method at the end of your Activity onCreate method or whenever you dynamically create new views:

private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
private static Typeface m_font = null;

public static Typeface getFont(Context p_context)
{
    if (null == m_font && null != p_context)
    {
        m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
    }
    return m_font;
}

public static void setViewGroupFont(ViewGroup p_viewGroup)
{
    if (null != p_viewGroup)
    {
        for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
        {
            View currChildView = p_viewGroup.getChildAt(currChildIndex);

            if (ViewGroup.class.isInstance(currChildView))
            {
                setViewGroupFont((ViewGroup) currChildView);
            }
            else
            {
                try
                {
                    Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);

                    setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
                }
                catch (NoSuchMethodException ex)
                {
                    // Do nothing
                }
                catch (Exception ex)
                {
                    // Unexpected error setting font
                }
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜